1

我有一个与此类似的排序规则:

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

我的问题是当我使用像,和出现的group by HOUR(date)小时但使用.2340

实际上他们消失的结果。

我该怎么做?

这样做的简单方法是什么?

有没有办法避免 24 个 ifs 语句?

我们可以避免创建另一个表吗?

4

2 回答 2

3

您将需要一个包含 24 小时的表,然后JOIN到它。如果您无法创建表,则可以在查询中创建它。请参阅此演示

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
于 2013-05-07T14:57:43.233 回答
1

如果您不想为此创建表,则可以使用枚举从 0 到 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
于 2013-05-07T15:08:11.730 回答