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