我有一个包含两列的表,Date为DateTime,Value为INT(3可能值为1,2,3)
表数据是这样的:
Date , Value
---------------------------------------
2016-01-01 10:34:00 1
2016-01-01 10:35:00 1
2016-01-01 10:36:00 1
2016-01-01 10:37:00 1
2016-01-01 10:38:00 1
2016-01-01 10:39:00 3
2016-01-01 10:40:00 3
2016-01-01 10:41:00 2
2016-01-01 10:42:00 2
2016-01-01 10:43:00 2
2016-01-01 10:44:00 1
2016-01-01 10:45:00 1
2016-01-01 10:46:00 1
2016-01-01 10:47:00 1
我需要一个Sql Query(特别是在MySQL中)来生成输出:
Start Date , End Date , value
---------------------------------
2016-01-01 10:34:00 , 2016-01-01 10:38:00 , 1
2016-01-01 10:39:00 , 2016-01-01 10:40:00 , 3
2016-01-01 10:41:00 , 2016-01-01 10:43:00 , 2
2016-01-01 10:44:00 , 2016-01-01 10:47:00 , 1
有可能吗? 请帮忙。谢谢
答案 0 :(得分:0)
最快的方法是使用变量。您需要定义分组参数,每次更改值时都会更改:
select min(date), max(date), value
from (select t.*,
(@grp := if(@v = value, @grp,
if(@v := value, @grp + 1, @grp + 1)
)
) as grp
from t cross join
(select @grp := 0, @v := -1) params
order by date
) t
group by grp, value;
答案 1 :(得分:0)
这里还有一个
SELECT min(my_date), max(my_date), val
FROM (
SELECT @nr := IF(@old_val = val, @nr, @nr := @nr +1) AS nr
, @old_val := val
, t.*
FROM onoff t
,(SELECT @nr:=0, @old_val='') AS tmp
ORDER BY my_date
) AS t1
GROUP BY nr
ORDER BY min(my_date);
表格
CREATE TABLE `onoff` (
`my_date` datetime NOT NULL,
`val` int(11) DEFAULT NULL,
PRIMARY KEY (`my_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `onoff` (`my_date`, `val`)
VALUES
('2016-01-01 10:34:00', 1),
('2016-01-01 10:35:00', 1),
('2016-01-01 10:36:00', 1),
('2016-01-01 10:37:00', 1),
('2016-01-01 10:38:00', 1),
('2016-01-01 10:39:00', 3),
('2016-01-01 10:40:00', 3),
('2016-01-01 10:41:00', 2),
('2016-01-01 10:42:00', 2),
('2016-01-01 10:43:00', 2),
('2016-01-01 10:44:00', 1),
('2016-01-01 10:45:00', 1),
('2016-01-01 10:46:00', 1),
('2016-01-01 10:47:00', 1);