I have a query that has the following
DATE ID Name
--- ------------ -----------
2012-02-07 11:24:53.000 00001-KK-12 Smith, JEN
2011-12-28 00:00:00.000 00001-KK-12 Bearson, Matt
2012-02-13 10:38:18.000 00003-KJ-12 Wick, Julian
What I need to do is to get the latest date for a given ID and then show the results
So in this case, it would be:
DATE ID Name
--- ------------ -----------
2012-02-07 11:24:53.000 00001-KK-12 Smith, JEN
2012-02-13 10:38:18.000 00003-KJ-12 Wick, Julian
I tried to use the Top(1) with a group by on ID based but was not successful
There are several ways to do this. One way is to use row_number. Its useful if there’s a possibility that there’s a tie on date and you want to arbitrarily pick one.
Another option is to use an ANTI JOIN (no aggregates no CTE) as follows but will return multiple results if there’s a tie for first for a given ID.