MySQL 中没有row_number()
,但您可以执行双连接来搜索上一行:
select
sum(case when cur.state = 0 then 0
else subtime(cur.timeCol, prev.timeCol)
end) as TotalOnTime
from YourTable cur
join YourTable prev
on prev.timeCol < cur.timeCol
left join YourTable inbetween
on prev.timeCol < inbetween.timeCol
and inbetween.timeCol < cur.timeCol
where inbetween.timeCol is null;
在 MySQL 中,您还可以使用变量,在这种情况下可能更有效:
set @total := '00:00:00';
set @lasttime := '00:00:00';
select
@total := addtime(@total, case
when state = 0 then 0
when @lasttime is null then 0
else subtime(timeCol, @lasttime)
end)
, @lasttime := timeCol
from YourTable
order by timeCol;
select 'Result = ', @total;
创建和填充测试表的代码:
DROP TABLE IF EXISTS YourTable;
CREATE TABLE YourTable (
timeCol time,
state bit
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
insert into YourTable values ('00:00:00', 0);
insert into YourTable values ('04:00:00', 1);
insert into YourTable values ('08:00:00', 0);
insert into YourTable values ('09:00:00', 1);
insert into YourTable values ('15:00:00', 0);
insert into YourTable values ('20:00:00', 1);
insert into YourTable values ('23:59:59', 0);