Group by should return 0 when grouping by hours. H

2019-08-04 17:45发布

I have a collcation similar to this one:

http://sqlfiddle.com/#!2/fecbc/3

My problem is I would like when I use group by HOUR(date) hours like 2, 3, and 4 appears but with 0.

Actually they disappear of the result.

How can I perform this?

What is the simply way to do this?

Is there a way to avoid 24 ifs statements?

Can we avoid to create another table?

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-04 18:07

If you don't want to create a table for this, you can use a subquery that enumerates the hours from 0 to 23:

SELECT
  v_hours.hr as hour,
  COUNT(id) AS hourCount
FROM
  (select 0 as hr union all
   select 1 as hr union all
   select 2 as hr union all
   select 3 as hr union all
   select 4 as hr union all
   select 5 as hr union all
   select 6 as hr union all
   select 7 as hr union all
   select 8 as hr union all
   select 9 as hr union all
   select 10 as hr union all
   select 11 as hr union all
   select 12 as hr union all
   select 13 as hr union all
   select 14 as hr union all
   select 15 as hr union all
   select 16 as hr union all
   select 17 as hr union all
   select 18 as hr union all
   select 19 as hr union all
   select 20 as hr union all
   select 21 as hr union all
   select 22 as hr union all
   select 23 as hr  
) v_hours
LEFT JOIN testing 
  ON HOUR(date) = v_hours.hr
GROUP BY
  v_hours.hr
ORDER BY v_hours.hr
查看更多
Deceive 欺骗
3楼-- · 2019-08-04 18:25

You will need a table that contains 24 hours, then JOIN to it. If you're not able to create a table, then you can create it inside your query. See this demo.

SELECT a.hr, IFNULL(b.hourCount, 0) hourCount
FROM 
  (SELECT 1 AS hr
  UNION ALL
  SELECT 2
  UNION ALL
  SELECT 3
  UNION ALL
  SELECT 4
  UNION ALL
  SELECT 5
  UNION ALL
  SELECT 6
  UNION ALL
  SELECT 7
  UNION ALL
  SELECT 8
  UNION ALL
  SELECT 9
  UNION ALL
  SELECT 10
  UNION ALL
  SELECT 11
  UNION ALL
  SELECT 12
  UNION ALL
  SELECT 13
  UNION ALL
  SELECT 14
  UNION ALL
  SELECT 15
  UNION ALL
  SELECT 16
  UNION ALL
  SELECT 17
  UNION ALL
  SELECT 18
  UNION ALL
  SELECT 19
  UNION ALL
  SELECT 20
  UNION ALL
  SELECT 21
  UNION ALL
  SELECT 22
  UNION ALL
  SELECT 23
  UNION ALL
  SELECT 0) a
LEFT JOIN
  (SELECT COUNT(id) AS hourCount, HOUR(date) AS hr
   FROM `testing`
   GROUP BY HOUR(date)) b ON b.hr = a.hr
查看更多
登录 后发表回答