SQL Server:从group by中选择最后一个结果

时间:2013-09-09 22:07:45

标签: sql sql-server sql-server-2008

我试图从2个类似的结果(最早的结果)中检索最后的结果

FromUser | ToUser | Message | Date
User1    | User2  | hi      | 01/01/2013 20:00
User1    | User2  | hi later| 01/01/2013 21:00
User5    | User2  | hi      | 01/01/2013 20:01
User5    | User2  | hi later| 01/01/2013 21:01

SELECT        
    CM.FromUser, CM.ToUser, CM.Message, CM.Date, 
    U.UserId, U.UserFullName, U.UserName, U.UserPhoto
FROM
    ConversationMessages AS CM 
INNER JOIN
    Users AS U ON U.UserName = CM.FromUser
WHERE
    CM.ToUser = @user
ORDER BY 
    CM.Date DESC 

它应该首先列出用户5 hi然后在用户1喜欢后面的第二个(用户5按日期更新)。只有最后一行基本按FromUser分组,然后按日期排序。我对sql毫无用处,在这里尝试了许多建议并且没有工作

2 个答案:

答案 0 :(得分:1)

您希望为此使用窗口函数,而不是group by

select FromUser, ToUser, Message, [Date], UserId, UserFullName, UserName, UserPhoto
from (SELECT CM.FromUser, CM.ToUser, CM.Message, CM.Date, U.UserId,
             U.UserFullName, U.UserName, U.UserPhoto,
             row_number() over (partition by CM.FromUser, CM.ToUser order by [Date] desc) as seqnum
      FROM ConversationMessages CM INNER JOIN
           Users U
           ON U.UserName = CM.FromUser
      WHERE  CM.ToUser = @user
     ) s
WHERE seqnum = 1
ORDER BY CM.Date DESC ;

答案 1 :(得分:1)

这是您正在寻找的标准SQL:

SELECT * FROM ConversationMessages cm1
LEFT JOIN ConversationMessages cm2
ON cm1.fromUser = cm2.fromUser AND cm1.date < cm2.date
WHERE cm2.date IS NULL AND cm1.toUser = 'User2'
ORDER BY cm1.date DESC

它应该适用于任何DBMS。当然,请确保使用适当的SQL Server变量替换User2

输出:

FromUser | ToUser | Message | Date
User5    | User2  | hi later| 01/01/2013 21:01
User1    | User2  | hi later| 01/01/2013 21:00

小提琴here