Mysql: Group by Hour, 0 if no data

前端 未结 3 600
时光说笑
时光说笑 2021-01-15 11:08

I have the following query:

SELECT count(*) as \'totalCalls\', HOUR(`end`) as \'Hour\'
FROM callsDataTable 
WHERE company IN (
    SELECT number 
    FROM pr         


        
3条回答
  •  走了就别回头了
    2021-01-15 11:32

    You need a Hour table and then do a left Outer Join with the Hour_table.

    Which will ensure that all hours will be returned. If hour doesn't exists in callsDataTable then count will be 0.

    Hours Table

    create table hours_table (hours int);
    
    insert into hours_table values(0);
    insert into hours_table values(1);
     ...
    insert into hours_table values(23);
    

    Query:

    SELECT count(HOUR(`end`)) as 'totalCalls', HT.Hours as 'Hour'
    FROM Hours_table HT left Outer join callsDataTable CD
    on HT.Hours = HOUR(`end`)
    WHERE company IN (
        SELECT number 
        FROM products 
        WHERE products.id IN (@_PRODUCTS)) 
        AND YEAR(`end`) = @_YEAR AND MONTH(`end`) = @_MONTH 
     group by HT.Hours
    

提交回复
热议问题