RDBMS :MySQL
时间列数据类型为日期时间
对于24小时工作日的每个小时,我需要检索 start_time 与小时匹配的行数或 end_time 大于或等于小时。
下面是我当前的查询,它返回我需要的数据但仅基于一小时。我可以遍历并在一天中的每个小时执行24个单独的查询,但我希望在一个查询中有这个。
SELECT COUNT(*) as total_online
FROM broadcasts
WHERE DATE(start_time) = '2018-01-01' AND (HOUR(start_time) = '0' OR
HOUR(end_time) >= '0')
有没有更好的方法来查询我需要的数据?或许以某种方式使用分组?谢谢。
答案 0 :(得分:0)
不确定我是否关注,但尝试这样的事情:
select datepart(hh, getdate()) , count(*)
from broadcasts
where datepart(hh, starttime) <=datepart(hh, endtime)
and cast(starttime as date)=cast(getdate() as date) and cast(endtime as date)=cast(getdate() as date)
group by datepart(hh, getdate())
答案 1 :(得分:0)
加入一个返回所有小时数的子查询:
SELECT h.hour_num, COUNT(*) AS total_online
FROM (SELECT 0 AS hour_num UNION SELECT 1 UNION SELECT 2 ... UNION SELECT 23) AS h
JOIN broadcasts AS b ON HOUR(b.start_time) = h.hour_num OR HOUR(b.end_time) >= h.hour_num
WHERE DATE(b.start_time) = '2018-01-01'
GROUP BY h.hour_num