从另一个ID分组的表中选择最近的(前1个)

时间:2012-04-03 21:03:04

标签: sql sql-server-2008

我有一个表格,其中包含与用户之间的消息。如何使用SQL选择用户发送的所有消息。我想通过MessageSenderUserID对结果进行分组。我也想只返回最近的每个收件人。

我试图在having子句中使用MAX,但似乎这不是正确的解决方案。

我最好将其描述为以下查询的组合:

SELECT TOP 1 MessageID, MessageSent, MessageSenderUserID, MessageRecipientUserID
FROM [Messaging_Message]
WHERE MessageSenderUserID = 799
ORDER BY MessageSent DESC

SELECT MessageSenderUserID
FROM [Messaging_Message]
GROUP BY MessageSenderUserID

谢谢!

3 个答案:

答案 0 :(得分:5)

我最近才学会了这种(最令人惊讶和有趣)的方式来获得一组中的前1项:

select top 1 with ties
    MessageID, 
    MessageSent, 
    MessageSenderUserID, 
    MessageRecipientUserID
from [Messaging_Message]
order by row_number() over (partition by MessageSenderUserID 
                            order by MessageSent desc)

按顺序依次执行 - 结果按部分分组并按排序键排序,从而导致每个组在第一行接收数字1。 With ties返回所有内容。哦应用机械师的快乐!

答案 1 :(得分:1)

WITH TestTableCTE AS
(
    SELECT RN = ROW_NUMBER() OVER(PARTITION BY MessageSenderUserID ORDER BY MessageSent DESC),
           MessageID, MessageSent, MessageSenderUserID, MessageRecipientUserID
    FROM   [Messaging_Message]
)

SELECT MessageID, MessageSent, MessageSenderUserID, MessageRecipientUserID FROM TestTableCTE WHERE RN=1

答案 2 :(得分:0)

这假设用户不能在同一时间发送多条消息(在这种情况下,它会为用户显示多条消息):

SELECT a.MessageID, a.MessageSent, a.MessageSenderUserID, a.MessageRecipientUserID
FROM Messaging_Message AS a
    JOIN (
        SELECT MessageSenderUserID, MAX(MessageSent) AS MessageSent
        FROM Messaging_Message
        GROUP BY MessageSenderUserID
    ) AS b ON a.MessageSenderUserID = b.MessageSenderUserID
        AND a.MessageSent = b.MessageSent