改变后如何获得价值

问题描述

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

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

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

SELECT disTINCT(status),time FROM test;

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

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

这是sql fiddlehttps://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