Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

SQL Server:Letztes Ergebnis aus Gruppieren nach auswählen

Sie möchten dafür Fensterfunktionen verwenden, anstatt 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 ;