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 に答える