简体   繁体   中英

Select Most Recent date

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'

I am trying to query it in a way that it only gives me records with most recent date but it is getting little confusing because I am already pulling data from 3 tables and not sure how to use MAX(date) here.

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 

ADDING MAX() Function to your date column and group by all the columns with you the Latest date for the combination of values in all other columns.

I'm assuming you want to filter by dbo.Team.Date .

Change your WHERE clause to:

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

Use GroupBy and Having:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM