我有一个表,我需要根据用户 ID 拉回 5 个最新记录并关闭文档 ID(无重复)。基本上,我正在跟踪访问过的页面并尝试拉回用户最近访问的 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 ║
╚══════════════════════════════════════════════╝
最佳答案
SELECT TOP 3 UserId, DocumentId, MAX(CreatedDate)
FROM MyTable
WHERE UserId = 71
GROUP BY UserId, DocumentId
ORDER BY MAX(CreatedDate) DESC
关于SQL Server 按顺序分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18704039/