Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I need to select records in a fairly complex way, and I'm stuck. My basic knowledge just can't find a way to pick out the records.I have a table :id articleid accountid date-- --------- --------- ----1 101 200 2007-02-092 102 200 2006-02-123 102 99 2007-01-024 101 200 2006-02-195 103 200 2006-09-226 102 99 2007-02-037 101 99 2006-11-088 103 200 2007-02-179 103 200 2006-12-21First of all I want to get all records where the accountid is 200.Second I want to only return one record for a distinct articleid.Third, the distinct articleid must be the record from the group of records with the same accountid/articleid that has the most recent date.So from the data above I need a select statement that will return :id articleid accountid date-- --------- --------- ----1 101 200 2007-02-092 102 200 2006-02-128 103 200 2007-02-17Any help will be much appreciated, thanks
tkizer
Almighty SQL Goddess
38200 Posts
Posted - 2007-02-21 : 17:40:19
I think this'll work:
SELECT id, t.articleid, t.accountid, t.[date]FROM YourTable yINNER JOIN ( SELECT accountid, articleid, MAX([date]) AS [date] FROM YourTable WHERE accountid = 200 GROUP BY accountid, articleid) tON y.accountid = t.accountid AND y.articleid = t.articleid