SQL Server组按顺序排列

时间:2013-09-09 17:49:19

标签: sql sql-server sql-server-2008 group-by sql-order-by

我有一个表,我需要根据userID拉回5条最新记录,并键入documentID(无重复项)。基本上,我正在跟踪访问过的页面并试图用户最近撤回3个页面。

示例数据:

╔══════════════════════════════════════════════╗
║UserID   DocumentID   CreatedDate             ║
╠══════════════════════════════════════════════╣
║  71         22       2013-09-09 12:19:37.930 ║
║  71         25       2013-09-09 12:20:37.930 ║
║  72          1       2012-11-09 12:19:37.930 ║
║  99         76       2012-10-10 12:19:37.930 ║
║  71         22       2013-09-09 12:19:37.930 ║
╚══════════════════════════════════════════════╝

如果UserID = 71,则需要查询结果:

╔══════════════════════════════════════════════╗
║UserID    DocumentID  CreatedDate             ║
╠══════════════════════════════════════════════╣
║  71         25       2013-09-09 12:20:37.930 ║
║  71         22       2013-09-09 12:19:37.930 ║
╚══════════════════════════════════════════════╝

4 个答案:

答案 0 :(得分:18)

SELECT TOP 3 UserId, DocumentId, MAX(CreatedDate)
FROM MyTable
WHERE UserId = 71
GROUP BY UserId, DocumentId
ORDER BY MAX(CreatedDate) DESC

答案 1 :(得分:1)

你可以试试这个:

SELECT DISTINCT USERID, 
                DOCUMENTID, 
                MAX(CREATEDDATE) 
                  OVER ( 
                    PARTITION BY USERID, DOCUMENTID) CREATEDDATE 
FROM   MYTABLE 
WHERE  USERID = 71 

查看SQL Fiddle上的工作示例。

祝你好运!

答案 2 :(得分:0)

您可以尝试使用CTEROW_NUMBER

这样的东西
;WITH Vals AS (
    SELECT UserID, 
           DocumentID, 
           ROW_NUMBER() OVER(PARTITION BY UserID, DocumnentID ORDER BY CreatedDate DESC) RowID
    FROM MyTable
)
SELECT TOP 3 *
FROM Vals
WHERE UserID = 71
AND RowID = 1

答案 3 :(得分:-1)

Select USERID,DOCUMENT ID 
FROM yourtable
QUALIFY ROW_NUMBER OVER(Partition by user id ORDER By document id Desc)<6

这适用于Teradata。希望这也适用于Sql Server,因为它主要是ANSI SQL。