考虑 SQL Server 2008 中的以下数据库表:
ActionID (PK) ActionType ActionDate UserID ContentID
1 'Create' '2013-05-26 18:40:00' 1 10
2 'Create' '2013-05-26 18:30:00' 2 10
3 'Edit' '2013-05-26 12:30:00' 5 12
4 'Edit' '2013-05-26 12:25:00' 5 12
5 'Delete' '2013-05-26 12:22:00' 6 12
我想编写一个按
ContentID
和 ActionType
分组的 SQL 查询,但返回具有最新 ActionDate
的行而忽略其他行,即使它们具有不同的 UserID
或其他列值。所以它应该返回的是:
ActionID (PK) ActionType ActionDate UserID ContentID
1 'Create' '2013-05-26 18:40:00' 1 10
3 'Edit' '2013-05-26 12:30:00' 5 12
5 'Delete' '2013-05-26 12:22:00' 6 12
但我不太清楚如何编写查询来做到这一点。
最佳答案
一种方法是使用 CTE(公用表表达式)。
使用此 CTE,您可以按某些标准对数据进行分区 - 即您的 ContentID
和 Actiontype
- 并让 SQL Server 为每个“分区”从 1 开始为所有行编号,按 ActionDate
排序。
所以尝试这样的事情:
;WITH Actions AS
(
SELECT
ActionID, ActionType, ActionDate, UserID, ContentID,
RowNum = ROW_NUMBER() OVER(PARTITION BY ContentID, ActionType ORDER BY ActionDate DESC)
FROM
dbo.YourTable
WHERE
......
)
SELECT
ActionID, ActionType, ActionDate, UserID, ContentID,
FROM
Actions
WHERE
RowNum = 1
ORDER BY
ActionDate DESC
这是否接近你正在寻找的?
关于SQL Server - 选择行,删除重复但保留最高日期的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16761591/