[英]SQL Server Group By Order By Where
I have a single table which I need to pull back the 5 most recent records based on a userID and keying off of documentID (no duplicates). 我有一个表,我需要根据userID拉回5个最近的记录并键入documentID(没有重复)。 Basically, I'm tracking visited pages and trying to pull back the 3 most recent by user. 基本上,我正在跟踪访问过的页面并试图用户最近撤回3个页面。
Sample data: 样本数据:
╔══════════════════════════════════════════════╗
║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 ║
╚══════════════════════════════════════════════╝
Desired query results if UserID = 71: 如果UserID = 71,则需要查询结果:
╔══════════════════════════════════════════════╗
║UserID DocumentID CreatedDate ║
╠══════════════════════════════════════════════╣
║ 71 25 2013-09-09 12:20:37.930 ║
║ 71 22 2013-09-09 12:19:37.930 ║
╚══════════════════════════════════════════════╝
SELECT TOP 3 UserId, DocumentId, MAX(CreatedDate)
FROM MyTable
WHERE UserId = 71
GROUP BY UserId, DocumentId
ORDER BY MAX(CreatedDate) DESC
You could try this: 你可以试试这个:
SELECT DISTINCT USERID,
DOCUMENTID,
MAX(CREATEDDATE)
OVER (
PARTITION BY USERID, DOCUMENTID) CREATEDDATE
FROM MYTABLE
WHERE USERID = 71
Take a look at the working example on SQL Fiddle . 看一下SQL Fiddle的工作示例。
Good Luck! 祝好运!
You could try using a CTE and ROW_NUMBER . 您可以尝试使用CTE和ROW_NUMBER 。
Something like 就像是
;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
Select USERID,DOCUMENT ID
FROM yourtable
QUALIFY ROW_NUMBER OVER(Partition by user id ORDER By document id Desc)<6
This works in Teradata. 这适用于Teradata。 Hope this works in Sql Server too as its mainly ANSI SQL. 希望这也适用于Sql Server,因为它主要是ANSI SQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.