I have a table in SQL server like so (Note the ID field is not unique):
-----------------------------------
| ID | IsAdamBrown | DateComplete |
| 1 | TRUE | 2017-01-01 |
| 1 | TRUE | 2017-01-03 |
-----------------------------------
I'd like to select one row for all the unique IDs in the table and the most recent 'DateComplete' for that ID.
My desired output in this case would be:
-----------------------------------
| ID | IsAdamBrown | DateComplete |
| 1 | TRUE | 2017-01-03 |
-----------------------------------
I've tried:
SELECT DISTINCT DateComplete, ID, IsAdamBrown
FROM thisTable
WHERE IsAdamBrown IS NOT NULL
GROUP BY DateComplete, ID, IsAdamBrown
ORDER BY DateComplete DESC
Unfortunately I still get the two date rows back. In MySQL I would group by just the first two rows and the ORDER BY
would make sure the DateComplete was the most recent. SQL servers requirement that the SELECT
fields match the GROUP BY
makes this impossible.
How can I get a single row back for each ID with the most recent DateComplete?
5条答案
按热度按时间8ftvxx2r1#
hrirmatl2#
You can get by
GROUP BY
withMAX()
ofDateComplete
wnvonmuf3#
You can using LIMIT
vfh0ocws4#
You can use this. I hope it will work for you.
daolsyd05#
You can use
ROW_NUMBER()
for grouping according toID
and a subquery to get the only first record with recent iscomplete. This will first sort your data according to id and recent iscomplete and then the first result for all the unique IDs