需求背景
一个统计接口,前端需要返回两个数组,一个是0-23的小时计数,一个是各小时对应的统计数。
思路 直接使用group by查询要统计的表,当某个小时统计数为0时,会没有该小时分组。思考了一下,需要建立辅助表,只有一列小时,再插入0-23共24个小时
create table hours_list ( hour int not null primary key )
先查小时表,再做连接需要查的表,即可将没有统计数的小时填充上0。这里由于需要查多个表中,create_time在每个小时区间内、且source_id等于查询条件的统计之和,所以union all了多张表
select t.hour, sum(t.hour_count) hourcount from (select hs. hour as hour, count(cs.record_id) as hour_count from cbc_hours_list hs left join cbc_source_0002 cs on hour (cs.create_time) = hs. hour and cs.create_time > #{starttime} and cs.create_time <= #{endtime} <#if sourceid?exists && sourceid !=''> and source_id = #{sourceid} </#if> group by hs. hour union all select hs.hour as hour, count(cs.record_id) as hour_count from cbc_hours_list hs left join cbc_source_hs cs on hour (cs.create_time) = hs. hour and cs.create_time > #{starttime} and cs.create_time <= #{endtime} <#if sourceid?exists && sourceid !=''> and source_id = #{sourceid} </#if> group by hs. hour union all select hs.hour as hour, count(cs.record_id) as hour_count from cbc_hours_list hs left join cbc_source_kfyj cs on hour (cs.create_time) = hs. hour and cs.create_time > #{starttime} and cs.create_time <= #{endtime} <#if sourceid?exists && sourceid !=''> and source_id = #{sourceid} </#if> group by hs. hour union all select hs.hour as hour, count(cs.record_id) as hour_count from cbc_hours_list hs left join cbc_source_his_0002 cs on hour (cs.create_time) = hs. hour and cs.create_time > #{starttime} and cs.create_time <= #{endtime} <#if sourceid?exists && sourceid !=''> and source_id = #{sourceid} </#if> group by hs. hour union all select hs.hour as hour, count(cs.record_id) as hour_count from cbc_hours_list hs left join cbc_source_his_hs cs on hour (cs.create_time) = hs. hour and cs.create_time > #{starttime} and cs.create_time <= #{endtime} <#if sourceid?exists && sourceid !=''> and source_id = #{sourceid} </#if> group by hs. hour union all select hs.hour as hour, count(cs.record_id) as hour_count from cbc_hours_list hs left join cbc_source_his_kfyj cs on hour (cs.create_time) = hs. hour and cs.create_time > #{starttime} and cs.create_time <= #{endtime} <#if sourceid?exists && sourceid !=''> and source_id = #{sourceid} </#if> group by hs. hour) t group by t.hour
效果
统计数为0的小时也可以查出来了。
到此这篇关于mysql按小时查询数据,没有的补0的文章就介绍到这了,更多相关mysql按小时查询数据内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!