如何创建一个MySQL查询以获取每月的每个日期的销售量(如日历)?

时间:2019-08-16 04:47:00

标签: mysql sql

我有三个表:产品发票发票详细信息
 enter image description here

我想为给定月份的每个日期生成每月销售报告,如下图所示。 enter image description here

我尝试了许多具有不同联接的查询,但没有得到所需的输出。如何通过如图2所示的查询获得所需的月度销售报告?

谢谢

1 个答案:

答案 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()