选择最近的日期

时间:2013-10-08 21:20:06

标签: sql sql-server

SELECT     dbo.Team.ID, dbo.Team.Comment, dbo.Team.Date, dbo.TeamName.Name, dbo.Contacts.ContactName 
FROM       dbo.Team 
INNER JOIN dbo.TeamName ON dbo.Team.ID = dbo.TeamName.id 
INNER JOIN dbo.Contacts ON dbo.Team.ContactID = dbo.Contacts.ContactID   
WHERE      dbo.TeamName.idstatus = 'Active'

我试图以一种方式查询它,它只给我最近日期的记录,但它变得有点混乱,因为我已经从3个表中提取数据而不知道如何在这里使用MAX(date)

3 个答案:

答案 0 :(得分:1)

SELECT     dbo.Team.ID, dbo.Team.Comment, MAX(dbo.Team.Date) LatestDate, dbo.TeamName.Name, dbo.Contacts.ContactName 
FROM       dbo.Team 
INNER JOIN dbo.TeamName ON dbo.Team.ID = dbo.TeamName.id 
INNER JOIN dbo.Contacts ON dbo.Team.ContactID = dbo.Contacts.ContactID   
WHERE      dbo.TeamName.idstatus = 'Active'
GROUP BY   dbo.Team.ID, dbo.Team.Comment, dbo.TeamName.Name, dbo.Contacts.ContactName 

将MAX()函数添加到您的日期列并按所有列分组,并列出所有其他列中值组合的最新日期。

答案 1 :(得分:0)

我假设您要按dbo.Team.Date进行过滤。

将您的WHERE条款更改为:

WHERE (dbo.TeamName.idstatus = 'Active') 
and (dbo.Team.Date=(select max(Date) from dbo.Team))

答案 2 :(得分:0)

使用GroupBy并拥有:

SELECT     dbo.Team.ID, dbo.Team.Comment, MAX(dbo.Team.Date), dbo.TeamName.Name,   dbo.Contacts.ContactName, 
FROM         dbo.Team 
INNER JOIN
dbo.TeamName ON dbo.Team.ID = dbo.TeamName.id 
INNER JOIN
dbo.Contacts ON dbo.Team.ContactID = dbo.Contacts.ContactID
WHERE     (dbo.TeamName.idstatus = 'Active')
GROUP BY dbo.Team.ID, dbo.Team.Comment, dbo.Team.Date, dbo.TeamName.Name, dbo.Contacts.ContactName
HAVING dbo.Team.Date = MAX(dbo.Team.Date)