我正在寻找一种方法来生成这样的东西,按照每个月(和每年)为给定客户分组所有发票(计数)和详细资料qty_shipped(总和)。
(示例输出)
CUSTOMER_NO , YR, MO, COUNT_INVOICES, TOTAL_QTY_SHIPPED
18 2015, 01, 30, 300
18 2014, 12, 65, 12323
18 2014, 11, 34, 4344
我有一个简单的发票(master pk:inv_id)表和相应的发票 - 详细信息(详细信息fk_inv_id),详细信息表由fk:inv_id连接到主服务器。表结构看起来像。
MASTER (Invoice)
inv_id
innvoice_number
customer_no
updated
DETAIL (invoices-detail )
invdet_id
inv_id
product_no
qty_shipped
qty_ordered
...
我正在尝试,但似乎没有用。它似乎错误计算了qty_shipped的总和
SELECT customer_no,YEAR(i.updated) as yr, MONTH(i.updated) as mnth,count(i.inv_id) as invoices_shipped ,
--subquery--
(SELECT count(idet.qty_shipped)
FROM invoice_details idet WHERE idet.inv_id=i.inv_id) as qty_shipped_TOTAL
--end subquery--
FROM invoice i WHERE status="SHIPPED" AND customer_no=18
GROUP BY YEAR(i.updated) DESC, MONTH(i.updated) DESC;
有什么建议吗?
答案 0 :(得分:0)
加入:
SELECT
i.customer_no,
YEAR(i.updated) as yr,
MONTH(i.updated) as mnth,
count(i.inv_id) as invoices_shipped,
sum(idet.qty_shipped)
FROM invoice i WHERE status="SHIPPED" AND customer_no=18
left join invoice_details idet on idet.inv_id=i.inv_id
GROUP BY i.customer_no, YEAR(i.updated), MONTH(i.updated)
order by YEAR(i.updated) DESC, MONTH(i.updated) DESC;