Mysql按天选择每个类别的总计

时间:2014-01-02 00:17:58

标签: mysql

我有三张桌子。

categories

  

id |编号

items

  

id |号码| CAT_ID

orders

  

id | item_id | DATE_TIME

我正在尝试为查询中的时间段内至少有一个订单的每个类别选择每日总订单。

期望的结果:

Date        Category Total
2013-12-01  001      6
2013-12-01  002      0
2013-12-01  003      1
2013-12-02  001      14
2013-12-02  002      2
2013-12-02  003      0
2013-12-03  001      11
2013-12-03  002      4
2013-12-03  003      4

我尝试了很多方法,但没有任何效果。我找到了这个http://www.richnetapps.com/using-mysql-generate-daily-sales-reports-filled-gaps/并相应地添加了一个日历表,但这也没有用。

SELECT calendar.datefield AS DATE, categories.number, count(orders.id) 
FROM categories
LEFT JOIN items on categories.id = items.cat_id
LEFT JOIN orders on items.id = order.item_id
RIGHT JOIN calendar ON DATE(orders.order_date) = calendar.datefield
WHERE calendar.datefield BETWEEN '2013-11-01' AND '2013-11-06'
GROUP BY DATE, categories.number asc

谢谢

1 个答案:

答案 0 :(得分:2)

更新:您可以这样做

SELECT d.date, d.cat_id, COALESCE(o.total, 0) total
  FROM
(
  SELECT c.date, i.cat_id
    FROM calendar c CROSS JOIN 
  (
    SELECT DISTINCT i.cat_id
      FROM orders o JOIN items i
        ON o.item_id = i.id
     WHERE o.order_date >= '2013-11-01'
       AND o.order_date < '2013-11-07'
  ) i
   WHERE c.date BETWEEN '2013-11-01' AND '2013-11-06'
) d LEFT JOIN 
(
  SELECT DATE(o.order_date) date, i.cat_id, COUNT(DISTINCT o.id) total
    FROM orders o JOIN items i
        ON o.item_id = i.id
     WHERE o.order_date >= '2013-11-01'
       AND o.order_date < '2013-11-07'
   GROUP BY DATE(o.order_date), i.cat_id
) o
     ON d.date = o.date
    AND d.cat_id = o.cat_id
 ORDER BY d.date, d.cat_id

一些解释:

  1. 在带有别名d的子查询中,我们会根据该段时间的订单创建日历和类别ID中所有日期的所有可能组合。
  2. 在具有别名o的子查询中,计算感兴趣的时间段中每个日期和类别ID的订单总数。
  3. 然后在外部选择中我们使用LEFT OUTER JOIN来确保我们在步骤1中生成的所有日期 - 类别ID组合都出现在最终结果集中。
  4. 输出:

    +------------+--------+-------+
    | date       | cat_id | total |
    +------------+--------+-------+
    | 2013-11-01 |      1 |     0 |
    | 2013-11-01 |      2 |     0 |
    | 2013-11-01 |      3 |     1 |
    | 2013-11-02 |      1 |     0 |
    | 2013-11-02 |      2 |     0 |
    | 2013-11-02 |      3 |     1 |
    | 2013-11-03 |      1 |     1 |
    | 2013-11-03 |      2 |     0 |
    | 2013-11-03 |      3 |     3 |
    | 2013-11-04 |      1 |     1 |
    | 2013-11-04 |      2 |     0 |
    | 2013-11-04 |      3 |     2 |
    | 2013-11-05 |      1 |     3 |
    | 2013-11-05 |      2 |     0 |
    | 2013-11-05 |      3 |     3 |
    | 2013-11-06 |      1 |     1 |
    | 2013-11-06 |      2 |     1 |
    | 2013-11-06 |      3 |     3 |
    +------------+--------+-------+
    

    这是 SQLFiddle 演示