我有一个包含插入/更新/删除操作的更改日志:
change_id | object_id | operation
----------+-----------+----------
1 | 1 | insert
2 | 2 | insert
3 | 1 | delete
4 | 1 | insert
5 | 3 | insert
6 | 2 | delete
7 | 4 | insert
8 | 3 | update
我只需要为每个object_id
选择最后一行,并将结果按change_id
排序。结果应如下所示:
change_id | object_id | operation
----------+-----------+----------
4 | 1 | insert
6 | 2 | delete
7 | 4 | insert
8 | 3 | update
我该怎么做?是否可以使用简单的查询,没有存储过程?
答案 0 :(得分:2)
SELECT c.change_id, c.object_id, c.operation
FROM
(
SELECT MAX(change_id) AS CID
FROM changelog
GROUP BY object_id
) s
INNER JOIN changelog c on c.change_id = s.CID
答案 1 :(得分:1)
;WITH MyCTE AS
(
SELECT change_id,
object_id,
operation,
ROW_NUMBER() OVER(PARTITION BY object_id ORDER BY change_id DESC) AS rn
FROM ChangeLog
)
SELECT change_id,
object_id,
operation
FROM MyCTE
WHERE rn = 1
<强> SQL Fiddle Demo 强>
答案 2 :(得分:1)
使用排名函数SQL Server Ranking Functions:
SELECT change_id, object_id, operation
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY object_id ORDER BY change_id DESC) as rownum,
change_id, object_id, operation
FROM yourtable
)a
WHERE rownum = 1
答案 3 :(得分:0)
&#34; last&#34;的概念如果添加捕获操作发生时间的时间戳列(例如LAST_UPDATE),则很容易建立。您将选择行LAST_UPDATE是最大值