0
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 by 方法时,它告诉我需要添加所有其他列...

Column 'Messages.FromUserID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

肯定有更好的办法?

4

1 回答 1

2

使用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
于 2012-10-10T12:01:15.733 回答