2014-01-27 174 views
0

我有這些表。T-SQL Group By With Distinct Value

用戶

|ID|Field1....| 

UserMessages

|ID|UserSenderId|UserReceiverId|Message|CreatedOn| 

UserSenderIdUserReceiverId是PK的FK User.Id

我想選擇每個會話的第一條消息用戶之間(像Facebook這樣的地方在左邊我看到的用戶和最後消息的第一個字符)

我這個查詢嘗試的列表,但我有同樣的情侶用戶

SELECT DISTINCT 
    UserMessages.* 
FROM 
    UserMessages 
JOIN 
    (SELECT 
     MAX(UserMessages.Id) AS IDMAX, 
     UserMessages.IdReceiver, 
     UserMessages.IdSender 
    FROM 
     UserMessages 
    WHERE 
     UserMessages.IdReceiver = @UserId OR UserMessages.IdSender = @UserId 
    GROUP BY 
     UserMessages.IdReceiver, UserMessages.IdSender) IDMAX ON IDMax.IDMAX = UserMessages.Id 

多個結果

UserMessages

|ID|UserSenderId|UserReceiverId|Message| 
    1|46|47|Hello 
    2|47|46|Hello! 
    3|46|48|Hey!! 
    4|50|46|How are you? 
    5|51|49| Hello 

考慮登錄用戶ID = 46,我想只選擇ID的消息2 3 4,其中id = 2是用戶46和47之間的最後一個(登錄用戶可能是發送者或接收者)

謝謝!

回答

2

你可以用row_number()來做到這一點。訣竅是將消息配對,而不管發送者和接收者是誰。您可以通過先放較小的ID,然後輸入較大的ID:

select um.* 
from (SELECT um.*, 
      row_number() over (partition by (case when idReceiver < idSender then idReceiver else idSender end), 
              (case when idReceiver < idSender then idSender else idReceiver end) 
           order by id desc 
           ) as seqnum 
    from UserMessages um 
    where um.IdReceiver = @UserId OR um.IdSender = @UserId 
    ) um 
where seqnum = 1; 
+0

謝謝!它的作用就像一個魅力;)現在我必須閱讀有關row_number();)再次感謝 – user1107078