MySQL按小時查詢資料,沒有的補0

2022-09-24 14:12:17 字數 2487 閱讀 9546

乙個統計介面,前端需要返回兩個陣列,乙個是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 > #

and cs.create_time <= #

and source_id = #

#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 > #

and cs.create_time <= #

and source_id = #

#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 > #

and cs.create_time <= #

and source_id = #

#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 > #

and cs.create_time <= #

and source_id = #

#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 > #

and cs.create_time <= #

unnhyrzxsid !=''>

and source_id = #

#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 > #

and cs.create_time <= #

and source_id = #

#if>

group by

hs. hour) t

group by

t.hour

統計數為0的小時也可以查出來了。

mysql按日期查詢資料 mysql按日期查詢資料

問題 mysql按日期查詢乙個月內的資料,查詢返回時結果集中只顯示有資料的結果 需求 查詢結果中假如當天沒有資料,自動填零並輸出 事件描述 sql語句 select date format date added,m.d as day,count product id as total from ht...

mysql 按小時,按天,按周等 統計

按周 select date format create time,y u weeks,count caseid count from tc case group by weeks 按月select date format create time,y m months,count caseid co...

按小時,天,周,月進行查詢

按小時統計 查詢當天存在的所有時刻 即00 23時刻 select sdays level 1 24 dates from select to date 2012 01 05 00 yyyy mm dd hh24 sdays,to date 2012 01 05 23 yyyy mm dd hh24...