SELECT
M.FromUserID,
UF.Fname + ' ' + UF.Sname As FullName,
UF.URL as Username,
Subject,
Body,
M.Ctime,
M.ViewedDate,
M.MessageID,
M.Starred,
M.Deleted,
M.ToUserID,
(SELECT TOP 1 Fname + ' ' + Sname as FullName FROM user_basics UB WHERE UB.UserID = M.ToUserID) as ToName,
(SELECT TOP 1 URL FROM user_basics UB WHERE UB.UserID = M.ToUserID) as ToUserName
FROM Messages M
LEFT JOIN User_Basics UF ON UF.userID = M.FromUserID
WHERE M.ToUserID = 1433 AND Deleted IS NULL ORDER BY M.Ctime DESC
我想显示一条消息历史记录,其中最新消息首先按用户名...
分组当我按方法使用group时,它告诉我需要添加所有其他列...
Column 'Messages.FromUserID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
必须有更好的方法吗?
答案 0 :(得分:3)
使用ROW_NUMBER() OVER (PARTITION BY M.FromUserID ORDER BY M.ViewedDate DESC)
:
WITH CTE AS
(
SELECT
M.FromUserID,
UF.Fname + ' ' + UF.Sname As FullName,
UF.URL as Username,
Subject,
Body,
M.Ctime,
M.ViewedDate,
M.MessageID,
M.Starred,
M.Deleted,
M.ToUserID,
(SELECT TOP 1 Fname + ' ' + Sname as FullName FROM user_basics UB WHERE UB.UserID = M.ToUserID) as ToName,
(SELECT TOP 1 URL FROM user_basics UB WHERE UB.UserID = M.ToUserID) as ToUserName,
RN = ROW_NUMBER() OVER (PARTITION BY M.FromUserID ORDER BY M.ViewedDate DESC)
FROM Messages M
LEFT JOIN User_Basics UF ON UF.userID = M.FromUserID
WHERE M.ToUserID = 1433
AND Deleted IS NULL
)
SELECT * FROM CTE
WHERE RN = 1
ORDER BY Ctime DESC