MySQL按小时查询数据,没有的补0

数据库 itxz 1个月前 (12-21) 43次浏览 0个评论

一个统计接口,前端需要返回两个数组,一个是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


IT学者 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:MySQL按小时查询数据,没有的补0
喜欢 (0)

您必须 登录 才能发表评论!