0

我有一个名为tblMsg用于存储消息的表。我想获取发件人发布的最后一条消息(表中的一列Message)。

这是我的查询

Select 
   Max(MsgId), Sender, Receiver, Contents, 
   convert(nvarchar(20), SendTime, 120) as SendTime
from 
   dbo.tblMessage 
where 
   Sender = @userName 
group by 
   Sender, Receiver, Contents, SendTime

这里的问题是我没有收到最后一条消息,而是收到了发件人发布的所有消息

4

2 回答 2

2

问题是您按所有列分组,而实际上您只想按 SenderID 列分组。这是一种方法,使用 CTE 和窗口函数获取最后一条消息或每个用户:

;WITH x AS 
(
  SELECT MsgId, Sender, Receiver, Contents, 
     SendTime = CONVERT(CHAR(20), SendTime, 120),
     rn = ROW_NUMBER() OVER (PARTITION BY Sender ORDER BY SendTime DESC)
  FROM dbo.tblMessage
)
SELECT MsgId, Sender, Receiver, Contents, SendTime
  FROM x
  WHERE rn = 1;

当然,如果您一次只跟踪一个发件人,您可以完全不分组:

SELECT TOP (1) MsgId, Sender, Receiver, Contents,
  SendTime = CONVERT(CHAR(20), SendTime, 120)
FROM dbo.tblMessage
WHERE Sender = @userName
ORDER BY SendTime DESC;
于 2013-03-26T11:34:12.847 回答
0
SELECT TOP 1 MsgId,Sender,Receiver,Contents,convert(nvarchar(20),SendTime,120) as SendTime
FROM dbo.tblMessage
WHERE Sender=@userName
ORDER BY MsgId DESC
于 2013-03-26T11:31:55.833 回答