Sun*_*oot 4 sql t-sql sql-server-2008
考虑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
Run Code Online (Sandbox Code Playgroud)
我想编写一个SQL查询,该查询按组分组ContentID
,ActionType
但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
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何编写查询来做到这一点.
一种方法是使用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
Run Code Online (Sandbox Code Playgroud)
这接近你正在寻找的东西吗?