2

我有一个表,其中包含来自用户的消息。如何使用 SQL 选择用户发送的所有消息。我想按 MessageSenderUserID 对结果进行分组。我还想只返回每个收件人最近的一个。

我尝试在有子句中使用 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

谢谢!

4

3 回答 3

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)

Trick is in order by - 结果按部分分组并按排序键排序,导致每个组接收第一行的数字 1。With ties返回所有。哦,应用机械师的喜悦!

于 2012-04-03T21:36:53.480 回答
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
于 2012-04-03T21:23:16.793 回答
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
于 2012-04-03T21:18:10.963 回答