如何按小时对结果进行分组,其中包括没有记录的小时数

时间:2014-06-17 17:19:52

标签: mysql sql database

我有一张包含所有订单的表格,我试图按小时分隔订单。 如果没有特定小时的记录,查询将忽略该小时,但我想要实现的是报告' 0' 0' 0那个小时。

我还加入了一张包含所有小时的临时表格。

SELECT sum(orders.price), hour(orders.time) as hour
FROM orders 
RIGHT JOIN dummy_time as dummy
ON hour(orders.time) = dummy.time
WHERE state = 1
AND (date(orders.time) = '2014-06-17' or orders.time is null)
GROUP BY hour

您可以在SQLFiddle

中查看我的查询

2 个答案:

答案 0 :(得分:1)

this您要找的是什么?对于是否显示总和顺序或是否显示0,它使用state = 1对state = 0的情况。如果不是,请告诉我你想要的结果。

答案 1 :(得分:1)

要获取dummy_time的所有行,请将条件从WHERE移至RIGHT JOIN。此外,从dummy.time中选择小时,这样您就可以获得所有时间。

使用COALESCE获取订单没有记录的0值。

SELECT COALESCE(sum(orders.price),0), dummy.time as hour
FROM orders 
RIGHT JOIN dummy_time as dummy
ON hour(orders.time) = dummy.time
AND orders.state = 1
AND orders.time BETWEEN '2014-06-17 00:00:00' AND '2014-06-17 23:59:59'
GROUP BY dummy.time

http://www.sqlfiddle.com/#!2/c7adb/2

下面查询的查询计划看起来比上面的查询更差但是因为您报告JOIN似乎是缓慢的主要来源,所以值得一试。在执行JOIN之前,下面的查询会减少行集。

SELECT 
  COALESCE(t1.orders_sum,0),
  t2.time
FROM
(
  SELECT 
    sum(orders.price) orders_sum, 
    hour(orders.time) orders_hour
  FROM orders 
  WHERE orders.state = 1
  AND orders.time BETWEEN '2014-06-17 00:00:00' AND '2014-06-17 23:59:59'
  GROUP BY hour(orders.time)
) t1 RIGHT JOIN dummy_time t2 ON t1.orders_hour = t2.time

http://www.sqlfiddle.com/#!2/0775b/1

另外,请确保您的表已编入索引

CREATE INDEX test_index1 ON orders (state,time);
CREATE INDEX test_index2 ON dummy_time (time);