MySQL按小时计算记录数,甚至是没有记录的小时数

时间:2014-02-17 16:56:11

标签: mysql sql database select

我想查询过去24小时内每小时表格中列值的平均值。即使在没有记录的时间内显示结果也很困难(在这些情况下,我应该打印平均值为0)

这是我到目前为止所拥有的:

SELECT HOUR(time), AVG(score) FROM place_rvw WHERE time >= NOW() - INTERVAL 1 DAY AND place_id = 1 ORDER BY HOUR(time);

现在(上午12点),我所拥有的唯一记录是晚上9点和晚上10点。因此,结果中只有两行。我希望它有24行(代表过去24小时中的每一行),如果一小时没有记录,则只显示平均值为0.

任何形式的帮助表示赞赏。谢谢!

编辑 我尝试了下面的查询,就像Stephan建议的那样,但它仍然显示相同的结果。理想的结果应该包含每小时代表的所有24行。有什么建议吗?

  SELECT za_hours.za_hour as hour, AVG(IFNULL(score,0)) as average_score
  FROM (
  SELECT 0 as za_hour
  UNION
  SELECT 1 as za_hour
  UNION
  SELECT 2 as za_hour
  UNION
  SELECT 3 as za_hour
  UNION
  SELECT 4 as za_hour
  UNION
  SELECT 5 as za_hour
  UNION
  SELECT 6 as za_hour
  UNION
  SELECT 7 as za_hour
  UNION
  SELECT 8 as za_hour
  UNION
  SELECT 9 as za_hour
  UNION
  SELECT 10 as za_hour
  UNION
  SELECT 11 as za_hour
  UNION
  SELECT 12 as za_hour
  UNION
  SELECT 13 as za_hour
  UNION
  SELECT 14 as za_hour
  UNION
  SELECT 15 as za_hour
  UNION
  SELECT 16 as za_hour
  UNION
  SELECT 17 as za_hour
  UNION
  SELECT 18 as za_hour
  UNION
  SELECT 19 as za_hour
  UNION
  SELECT 20 as za_hour
  UNION
  SELECT 21 as za_hour
  UNION
  SELECT 22 as za_hour
  UNION
  SELECT 23 as za_hour
) za_hours
LEFT JOIN place_rvw 
  ON za_hours.za_hour = HOUR(time)
  AND
  time >= NOW() - INTERVAL 1 DAY 
  AND place_id = 1 
GROUP BY
  za_hours.za_hour
ORDER BY za_hours.za_hour

4 个答案:

答案 0 :(得分:2)

1)创建一个包含24行的表,每行一个,持续一小时。

2)与你的桌子做一个左外连接。

解决方案如下所示: SQL fiddle

由于过滤

,您仍未获得结果

答案 1 :(得分:1)

您需要以下内容:

SELECT 
  za_hours.za_hour, 
  AVG(IFNULL(score,0)) 
FROM (
  SELECT 0 as za_hour
  UNION
  SELECT 1 as za_hour
  ...
  SELECT 23 as za_hour
) za_hours
LEFT JOIN place_rvw 
  ON za_hours.za_hour = HOUR(time)
WHERE 
  time >= NOW() - INTERVAL 1 DAY 
  AND place_id = 1 
GROUP BY
  za_hours.za_hour
ORDER BY za_hours.za_hour

za_hours是一个包含所有小时(0,1 .. 24)的tmp表,这样当你没有某个小时的记录时,你仍会有结果(即使它们将为零)

答案 2 :(得分:0)

您的WHERE语句使其不显示包含0的行。在WHERE语句中使用OR执行以下操作:OR time = 0

答案 3 :(得分:0)

尝试更改此内容:

WHERE 
  time >= NOW() - INTERVAL 1 DAY 
  AND place_id = 1 

到此:

WHERE 
  (time >= NOW() - INTERVAL 1 DAY
  or time is null)
  AND place_id = 1