改变后如何获得价值

时间:2020-11-09 15:21:05

标签: mysql sql datetime gaps-and-islands

假设我有一个简单的数据库,例如:

CREATE TABLE test (
  id INT,
  time datetime,
  status integer
);

和一些数据:

INSERT INTO test (id, time, status) VALUES (1, '2020-11-09 10:00', 256);
INSERT INTO test (id, time, status) VALUES (2, '2020-11-09 11:00', 256);
INSERT INTO test (id, time, status) VALUES (3, '2020-11-09 11:20', 512);
INSERT INTO test (id, time, status) VALUES (4, '2020-11-09 11:35', 512);
INSERT INTO test (id, time, status) VALUES (5, '2020-11-09 11:40', 1024);
INSERT INTO test (id, time, status) VALUES (6, '2020-11-09 11:45', 1024);
INSERT INTO test (id, time, status) VALUES (7, '2020-11-09 11:48', 1024);
INSERT INTO test (id, time, status) VALUES (8, '2020-11-09 12:00', 0);
INSERT INTO test (id, time, status) VALUES (9, '2020-11-09 12:01', 0);
INSERT INTO test (id, time, status) VALUES (10, '2020-11-09 12:05', 0);
INSERT INTO test (id, time, status) VALUES (11, '2020-11-09 12:07', 0);
INSERT INTO test (id, time, status) VALUES (12, '2020-11-09 12:09', 512);

我想做的是状态更改后仅保留行。 简单的DISTINCT仅给我1个值,所以并不容易:

SELECT DISTINCT(status), time FROM test;

所以我的预期结果应具有ID: 1、3、5、8和12

我需要分组吗?感谢您的帮助。

这是SQL Fiddle: https://www.db-fiddle.com/f/nixj1LCKLJCfeXk9q7233P/0

1 个答案:

答案 0 :(得分:2)

您可以使用lag()

select *
from (
    select t.*, lag(status) over(order by time) lag_status
    from test t
) t
where not status <=> lag_status

这需要MySQL 8.0。在早期版本中,一种方法使用相关子查询:

select t.*
from test t
where not status <=> (
    select t1.status
    from test t1
    where t1.time < t.time 
    order by t1.time desc
    limit 1
)

https://www.db-fiddle.com/f/nixj1LCKLJCfeXk9q7233P/1