Mysql每天按类别选择计数

时间:2013-12-31 19:06:25

标签: mysql sql

我有三张桌子。

categories

  

id |名称

items

  

id |名字| CATEGORY_ID

orders

  

id | item_id | date_time | transaction_code

现在,如何在查询中的每一天为每个类别选择具有特定交易代码的总订单。

期望的结果:

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

编写此查询的最有效方法是什么。

这是我到目前为止所尝试的:

SELECT DATE(od.trans_date) AS Date, ct.number AS Category, COUNT(od.id) AS Total 
from orders od
JOIN items im ON od.item_id = im.id
JOIN categories ct ON im.category_id = ct.id
WHERE od.trans_date BETWEEN '2013-12-01 00:00:00' AND '2013-12-03 23:59:59'
AND (od.transaction_code = 17 OR od.transaction_code = 15)
GROUP BY DATE(od.trans_date), ct.number ASC;

谢谢

1 个答案:

答案 0 :(得分:1)

我建议您将JOINS更改为LEFT JOINS,以便您的结果包含没有任何商品的订单......

SELECT DATE(od.trans_date) AS Date, ct.number AS Category, COUNT(od.id) AS Total 
from orders od
LEFT JOIN items im ON od.item_id = im.id
LEFT JOIN categories ct ON im.category_id = ct.id
WHERE od.trans_date BETWEEN '2013-12-01 00:00:00' AND '2013-12-03 23:59:59'
AND (od.transaction_code = 17 OR tr.transaction_code = 15)
GROUP BY DATE(od.trans_date), ct.number ASC;

此外,您可能需要切换JOINS的顺序,以便显示所有类别,而不是所有订单。

SELECT DATE(od.trans_date) AS Date, ct.number AS Category, COUNT(od.id) AS Total 
FROM categories ct
LEFT JOIN items im ON ct.id = im.category_id
LEFT JOIN orders od ON im.id = od.item_id
WHERE od.trans_date BETWEEN '2013-12-01 00:00:00' AND '2013-12-03 23:59:59'
AND (od.transaction_code = 17 OR tr.transaction_code = 15)
GROUP BY DATE(od.trans_date), ct.number ASC;