【发布时间】:2020-11-09 15:21:05
【问题描述】:
假设我有一个简单的数据库,例如:
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
【问题讨论】:
-
请注意,DISTINCT 不是函数
标签: mysql sql datetime gaps-and-islands