MS SQL - 只为ID选择一行

时间:2014-09-08 14:17:39

标签: sql sql-server greatest-n-per-group

我有一个包含插入/更新/删除操作的更改日志:

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

我该怎么做?是否可以使用简单的查询,没有存储过程?

4 个答案:

答案 0 :(得分:2)

SQL Fiddle

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是最大值