這篇文章主要介紹了MySQL按小時查詢數(shù)據(jù),沒有的補0,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
需求背景
一個統(tǒng)計接口,前端需要返回兩個數(shù)組,一個是0-23的小時計數(shù),一個是各小時對應的統(tǒng)計數(shù)。
思路 直接使用group by查詢要統(tǒng)計的表,當某個小時統(tǒng)計數(shù)為0時,會沒有該小時分組。思考了一下,需要建立輔助表,只有一列小時,再插入0-23共24個小時
CREATE TABLE hours_list (
hour int NOT NULL PRIMARY KEY
)
先查小時表,再做連接需要查的表,即可將沒有統(tǒng)計數(shù)的小時填充上0。這里由于需要查多個表中,create_time在每個小時區(qū)間內(nèi)、且SOURCE_ID等于查詢條件的統(tǒng)計之和,所以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
效果
統(tǒng)計數(shù)為0的小時也可以查出來了。
到此這篇關于MySQL按小時查詢數(shù)據(jù),沒有的補0的文章就介紹到這了,更多相關MySQL按小時查詢數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
來源:腳本之家
鏈接:https://www.jb51.net/article/202439.htm
申請創(chuàng)業(yè)報道,分享創(chuàng)業(yè)好點子。點擊此處,共同探討創(chuàng)業(yè)新機遇!