如何在变化后才获得价值

How to get value only after change

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

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

我需要分组吗?将不胜感激。

这里是SQLFiddle: https://www.db-fiddle.com/f/nixj1LCKLJCfeXk9q7233P/0

您可以使用 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