根据一个字段选择与之前记录相比更改的记录

时间:2015-05-27 05:51:47

标签: sql-server

考虑以下示例数据

| SN |        DateTime       | Status |
|----|-----------------------|--------|
|  1 | '2015-01-01 00:30:00' | OPEN   |
|  2 | '2015-01-01 00:35:00' | OPEN   |
|  3 | '2015-01-01 00:40:00' | CLOSED |
|  4 | '2015-01-01 00:50:00' | OPEN   |
|  5 | '2015-01-01 01:10:00' | OPEN   |
|  6 | '2015-01-01 01:15:00' | CLOSED |
|  7 | '2015-01-01 01:20:00' | CLOSED |
|  8 | '2015-01-01 01:30:00' | OPEN   |
|  9 | '2015-01-01 01:40:00' | OPEN   |
| 10 | '2015-01-01 01:52:00' | OPEN   |
| 11 | '2015-01-01 01:55:00' | CLOSED |
| 12 | '2015-01-01 02:15:00' | OPEN   |
| 13 | '2015-01-01 02:30:00' | OPEN   |

我需要选择列的值为' Status'从它以前的记录改变了。应始终返回第一条记录。

我可以在SQL Server中使用For循环,但我想要一个更好的解决方案。是否可以在单个SELECT语句中执行此操作?查询应返回序列为1,3,4,6,8,11和12的行。

3 个答案:

答案 0 :(得分:8)

您可以使用LAG获取以前的Status值,然后在外部查询的WHERE子句中使用此值来获取所需内容:

SELECT SN, [DateTime], Status 
FROM (
   SELECT SN, [DateTime], Status, 
          LAG(Status) OVER (ORDER BY [DateTime]) AS prevStatus
   FROM mytable ) t
WHERE COALESCE(prevStatus, '') <> Status

Demo here

答案 1 :(得分:2)

或者没有LAG,您可以使用此查询

select * from (SELECT TOP 1 SN, [DateTime], Status from mytable  order by SN) as s
UNION ALL
SELECT T.SN, t.[DateTime], t.Status 
FROM mytable t
    inner join mytable t2
    on t.SN=t2.SN+1 AND t.status <> t2.status

答案 2 :(得分:1)

我们可以使用Union运算符,然后自己加入Id + 1

上的表
select * from Delta where id = 1 
UNION 
select  D.*from 
Delta D JOIN Delta DL On D.Id  = Dl.Id +1  
AND
D.Status <> DL.Status

SQLFiddle