I’ve a Table as below
ID |FromId |ToId |Message|DateTime
------------------------------------------
1 |1 |2 |a |15:00
2 |1 |2 |b |15:01
3 |1 |2 |c |15:02
4 |2 |1 |d |15:03
5 |3 |1 |e |15:04
6 |3 |1 |f |15:05
7 |1 |3 |g |15:06
what I want to get is Every last message of Peers.
For example: User 1 and user 2 has 4 messages (ID:1,2,3,4) and user 1 and user 3 has 3 messages (ID:5,6,7)
I want to get only latest Message record from users, I need a SQL query which will give the result like this:
*sql code here ? -- I need this.
result (for: where UserID=1) :
ID |FromId |ToId |Message|DateTime
------------------------------------------
4 |2 |1 |d |15:03
7 |1 |3 |g |15:06
Any Ideas ? I’ve tried with Distinct etc. but it didn’t worked somehow. Please help.
Sorry Guys I guess I forgot to mention that I need the latest record from Peer, not the latest record from one user, for example for user 1 and user 2 I need the latest record from them, no mather which one is From or which one is To.. I need the latest record from both which is ID 4 in our case no other records.
If Sql Server 2005+, you might use row_number() over ( … ) to group, order and number records, and then retrieve only the ones being first in their group: