SQL分组:用户之间的最新记录

时间:2009-06-21 11:26:01

标签: sql grouping

也许我有一个非常糟糕的一天,但是有人可能会帮助我解决这个问题:

MessageID | SendingUserID | ReceivingUserID
-------------------------------------------
1073      | 1002          | 1001
1065      | 1001          | 1002
1076      | 1008          | 1002

分为:

MessageID | SendingUserID | ReceivingUserID
-------------------------------------------
1073      | 1002          | 1001
1076      | 1008          | 1002

因此,只列出了两个用户之间的最新消息?

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT Message.*
FROM Message
WHERE Message.MessageID IN
(SELECT MAX(MessageID) FROM Message 
    GROUP BY 
        CASE WHEN ReceivingUserID > SendingUserID 
            THEN ReceivingUserID ELSE SendingUserID END,
        CASE WHEN ReceivingUserID > SendingUserID
            THEN SendingUserID ELSE ReceivingUserID END
)

答案 1 :(得分:0)

独家自我加入方式:

select *
from YourTable a
left join YourTable b 
    on (
        (a.SendingUserID = b.SendingUserID
        and a.ReceivinggUserID = b.ReceivingUserID)
        or (a.SendingUserID = b.ReceivingUserID
        and a.ReceivinggUserID = b.SendingUserID)
    ) and b.messageid > a.messageid
 where b.messageid is null

“b”上的联接搜索相同用户之间的后续消息。 WHERE子句筛选没有后续消息的消息。这为您提供了每对用户之间的最新消息。

答案 2 :(得分:0)

您可以在SQL Server 2005及更高版本中使用CTE(公用表表达式)来确保两个用户ID在较大的用户ID之前总是较小的,然后只获得每个组合的最大值:

WITH Messages(MessageID, User1, User2)
AS 
(
    SELECT
        MessageID,
        CASE 
          WHEN SendingUserID < ReceivingUserID
          THEN SendingUserID
          ELSE ReceivingUserID 
        END as 'User1',
        CASE 
          WHEN SendingUserID < ReceivingUserID
          THEN ReceivingUserID 
          ELSE SendingUserID
        END as 'User2'
    FROM 
        MyMessages
)
SELECT 
    MessageID, User1, User2 
FROM 
    Messages m1
WHERE
    MessageID = (SELECT MAX(MessageID) FROM  Messages m2 
                 WHERE m1.User1 = m2.User1 AND m1.User2 = m2.User2)

CTE内部的SELECT会像这样“订购”你的消息:

MessageID   User1   User2
  1065       1001    1002
  1073       1001    1002
  1076       1002    1008

和基于此CTE的外部SELECT只需为(User1,User2)的每个组合选择最大MessageID的条目。

马克