需求背景
一個(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ì)沒(méi)有該小時(shí)分組。思考了一下,需要建立輔助表,只有一列小時(shí),再插入0-23共24個(gè)小時(shí)
CREATE TABLE hours_list (
hour int NOT NULL PRIMARY KEY
)
先查小時(shí)表,再做連接需要查的表,即可將沒(méi)有統(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ù),沒(méi)有的補(bǔ)0的文章就介紹到這了,更多相關(guān)MySQL按小時(shí)查詢數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 詳解MySQL子查詢(嵌套查詢)、聯(lián)結(jié)表、組合查詢
- 詳解MySQL的sql_mode查詢與設(shè)置
- MySQL 子查詢和分組查詢
- MySQL 分組查詢和聚合函數(shù)
- Mysql 查詢JSON結(jié)果的相關(guān)函數(shù)匯總
- MySQL 查詢的排序、分頁(yè)相關(guān)
- MySql查詢時(shí)間段的方法
- MySQL中基本的多表連接查詢教程
- MySQL里面的子查詢實(shí)例
- 詳解mysql 組合查詢