Here is my table structure:-
Table01
ID Name FkID dateTime
1 John 1 2012-06-01
2 Peter 2 2012-06-02
3 Penny 2 2012-06-03
4 Patty 3 2012-06-01
I tried this query but 🙁
select *
from Table01
where FkID in
(SELECT FkID FROM Table01 GROUP BY FkID HAVING ( COUNT(PkID) < 2 ))
order by dateTime desc
Desired Results:-
1 John 1 2012-06-01
3 Penny 2 2012-06-03
4 Patty 3 2012-06-01
I need unique results by FkID but from duplicate FkID I need to pick row up by latest datetime. Any guide line please.
You can use ROW_NUMBER to achieve that.
I used a Common Table Expression (the
WITHstatement), but you can do it just as well with a normal subquery. But really,ROW_NUMBER()is a blessing when you are want to work with grouped data (or PARTITION’ed, so to say).