我想创建一个月结单
Tables
Product (id, name, price)
Invoice (id, date)
Invoice_item (id, invoice_id, product_id, quantity)
样本数据:
product
id | name | price
1 | apple | 10
2 | beer | 20
3 | shoe | 40
invoice
id | date
1 | 2013-01-21
2 | 2013-01-29
3 | 2013-02-02
invoice_item
id | invoice_id | product_id | quantity
1 | 1 | 1 | 2
2 | 1 | 2 | 1
3 | 2 | 3 | 1
4 | 3 | 2 | 2
我想要这个结果:
product.id | product.name | year(invoice.date) | month(invoice.date) | count | sum
1 | apple | 2013 | 01 | 2 | 20
1 | apple | 2013 | 02 | 0 (or null) | 0 (or null)
2 | beer | 2013 | 01 | 1 | 20
2 | beer | 2013 | 02 | 2 | 40
3 | shoe | 2013 | 01 | 1 | 40
3 | shoe | 2013 | 02 | 0 (or null) | 0 (or null)
这是我做的代码:
SELECT * FROM (
SELECT product prod,
(SELECT date FROM invoice
GROUP BY YEAR(date), MONTH(date)) grpdate) p
LEFT JOIN invoice_item ii
ON ii.product_id = p.id
LEFT JOIN invoice i
ON ii.invoice_id=i.id
GROUP BY p.id, YEAR(date), MONTH(date),
IF(YEAR(date) = YEAR(grpdate), YEAR(date), null),
IF(MONTH(date) = MONTH(grpdate), MONTH(date), null)