问题描述
start | end
2020-07-25 20:37:00 2020-07-25 20:44:00
2020-07-25 21:37:00 2020-07-25 22:44:00
2020-07-26 07:11:00 2020-07-27 10:50:00
...
最后,我想要一个直方图,该直方图显示一天中的每个小时每小时有多少个日期范围“重叠”。 因此,生成的直方图由24条组成。
如何在sql for MysqL中做到这一点? (旁注:我正在使用TypeORM,但是我能够编写普通的sql语句)
我只发现用TIMESTAMPDIFF
按各个间隔的长度进行计算和分组的解决方案,但这不是我想要实现的。
将来,我可能想显示相同的直方图,而不是每小时,而是一天中的每分钟或一个月中的每一天,依此类推。但是我认为,一旦我有了查询的概念,这样做就很简单:)
解决方法
一种方法是蛮力方法:
with recursive hours as (
select 0 as hh
union all
select hh + 1
from hours
where hh < 23
)
select h.hh,count(t.start)
from hours h left join
t
on start >= '2020-07-25' + interval h.hh hour and
end < '2020-07-25' + interval (h.hh + 1) hour
where end < '2020-07-25' + interval 1 day and
start >= '2020-07-25'
group by h.hh
order by h.hh;