2013-03-26 54 views
0

我有一個用於存儲消息的名爲tblMsg的表。我想獲取發件人發佈的最後一條消息(表Message中的一列)。在SQL Server 2005中使用MAX返回所有行而不是最後一行

這裏是我的查詢

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 

這裏的問題是不是得到我得到了張貼的所有發件人

回答

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; 
0
SELECT TOP 1 MsgId,Sender,Receiver,Contents,convert(nvarchar(20),SendTime,120) as SendTime 
FROM dbo.tblMessage 
WHERE [email protected] 
ORDER BY MsgId DESC 
相關問題