我尝试了许多具有不同联接的查询,但没有得到所需的输出。如何通过如图2所示的查询获得所需的月度销售报告?
谢谢
答案 0 :(得分:1)
您可以使用条件聚合:
select p.p_name,
sum(case when day(i.i_date) = 1 then id.id_quantity else 0 end) as day_01,
sum(case when day(i.i_date) = 1 then id.id_quantity else 0 end) as day_02,
. . . -- fill in for the rest of the days
sum(case when day(i.i_date) = 1 then id.id_quantity else 0 end) as day_31
from invoice i join
invoice_detail id
on id.id_invoice = i.i_id
product p
on id.id_product = p.p_id
where i.i_date >= '2019-08-01' and
i.i_date < '2019-09-01'
group by p.p_name;
唯一需要注意的是对日期的过滤,因此您只有一个月的数据,并且在该月的某天使用day()
。