我的问题是我没有得到我需要的正确输出。
我有three tables
产品
id title
1 aaa
2 bbb
3 ccc
订单
id order_date
1 01-20-2016
2 02-27-2016
3 03-29-2016
ORDER_DETAILS
id prod_id order_id quantity
1 1 1 1
2 3 1 1
3 2 2 2
4 1 2 1
5 3 2 1
6 2 3 1
7 1 3 2
不期望的输出
title date Quantity
aaa January 2
aaa February 4
aaa March 3
我期待的输出
title date quantity
aaa January 1
aaa Febuary 1
aaa March 2
bbb January 0
bbb Febuary 2
bbb March 1
ccc January 1
ccc February 1
ccc March 0
这是我目前的查询。
SELECT products.title, DATE_FORMAT(orders.order_date, '%M') as date, SUM(order_details.quantity) as quantity
FROM products, orders, order_details
WHERE products.id = order_details.product_id and orders.id = order_details.order_id
GROUP BY date
有人可以帮助我获取expected output
吗?提前谢谢。
答案 0 :(得分:0)
您的GROUP BY缺少标题字段,因此只使用了月份
尝试
GROUP BY title, date
答案 1 :(得分:0)
您只按日期对结果进行分组,因此例如对于1月,它将总结以下几行:
aaa January 1
bbb January 0
ccc January 1
,输出将是
aaa January 2 (sum of 1+0+1)
使用
GROUP BY title, date