MySQL选择group by和empty值

时间:2017-11-03 14:08:54

标签: mysql sql

我们假设我的商店从10点到15点开放,销售将在下表中保存时间戳:

+----------+---------------------+---------------+
| store_id | sales_date          | sales_amount  |
+----------+---------------------+---------------+
|        1 | 2017-11-03 10:32:44 | 100.00        | 
|        1 | 2017-11-03 10:33:49 | 150.00        |
|        1 | 2017-11-03 11:08:24 | 120.00        |
|        1 | 2017-11-03 13:33:57 | 200.00        |
|        2 | 2017-11-03 12:37:34 | 100.00        |
|        2 | 2017-11-03 15:23:49 | 200.00        |
+----------+---------------------+---------------+

我想使用chart.js显示图表,范围从10到15。

我尝试了以下SQL:

SELECT store_id, HOUR(sales_date) as group_hour, sum(sales_amount) as sales_sum 
FROM sales 
GROUP BY store_id, group_hour

我的当前结果是

+----------+-------------+---------------+
| store_id | group_hour  | sales_sum     |
+----------+-------------+---------------+
|        1 | 10          | 250.00        | 
|        1 | 11          | 120.00        |
|        1 | 13          | 200.00        |
|        2 | 12          | 100.00        |
|        2 | 15          | 200.00        |
+----------+-------------+---------------+

我的预期结果

+----------+-------------+---------------+
| store_id | group_hour  | sales_sum     |
+----------+-------------+---------------+
|        1 | 10          | 250.00        | 
|        1 | 11          | 120.00        |
|        1 | 12          | 0.00          |
|        1 | 13          | 200.00        |
|        1 | 14          | 0.00          |
|        1 | 15          | 0.00          |
|        2 | 10          | 0.00          |
|        2 | 11          | 0.00          |
|        2 | 12          | 100.00        |
|        2 | 13          | 0.00          |
|        2 | 14          | 0.00          |
|        2 | 15          | 200.00        |
+----------+-------------+---------------+

有没有机会用MySQL做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用:

SELECT b.store_id, b.group_hour, IFNULL(sales_sum, 0) AS sales_sum
FROM 
(
 SELECT store_id, HOUR(sales_date) as group_hour, sum(sales_amount) as sales_sum 
 FROM sales 
 GROUP BY store_id, group_hour
) a
RIGHT OUTER JOIN 
(
  SELECT *
  FROM
  (
   SELECT DISTINCT store_id
   FROM sales
  ) all_stores
  CROSS JOIN
  (
   SELECT 10 as group_hour
   UNION ALL
   SELECT 11
   UNION ALL
   SELECT 12
   UNION ALL
   SELECT 13
   UNION ALL
   SELECT 14
   UNION ALL
   SELECT 15
  ) all_hours
) b
ON a.store_id = b.store_id AND a.group_hour = b.group_hour
ORDER BY 1, 2

我正在使用RIGHT OUTER JOIN与包含所有商店和所有小时(从10到15)的表格。