14

我有一个表,我需要根据用户 ID 拉回 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

4 回答 4

28
SELECT TOP 3 UserId, DocumentId, MAX(CreatedDate)
FROM MyTable
WHERE UserId = 71
GROUP BY UserId, DocumentId
ORDER BY MAX(CreatedDate) DESC
于 2013-09-09T17:56:13.603 回答
1

您可以尝试使用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
于 2013-09-09T17:55:15.920 回答
1

你可以试试这个:

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

查看SQL Fiddle上的工作示例。

祝你好运!

于 2013-09-09T18:02:25.160 回答
-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。

于 2013-09-09T18:00:20.887 回答