我有payment
数据表(MySQL)记录所有付款。我想按日期对所有付款进行分组。实际上,我想按月对他们进行分组,以分析他们在特定月份获得的收入。如果特定月份没有付款,我需要将其设置为0。
这是我的SQL代码。
SELECT SUM(p.sub_total) as sold_income , month(p.invoice_date) as income_month ,MONTHNAME(p.invoice_date) as month_name, YEAR(p.invoice_date) as income_year FROM payment p where (p.invoice_date BETWEEN '2018-01-01' AND '2018-08-01') GROUP BY DATE_FORMAT(p.invoice_date, '%Y%m')
从这段代码中,我得到以下输出:
我在“ 2018-01-01”和“ 2018-08-01”之间进行了搜索。因此应该有7个月和7个结果。如果第1个月(1月)没有付款,我想要sold_income = 0
;
我该怎么做?请帮助我。...
答案 0 :(得分:1)
生成日期并与此表格一起加入并投影结果
SELECT SUM(p.sub_total) as sold_income , month(C_date ) as income_month ,MONTHNAME(C_date ) as month_name, YEAR(C_date ) as income_year from
(
select * from
(select adddate('1970-01-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) C_date from
(select 0 t0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 t3 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 t4 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where C_date between '2017-08-01' and '2018-12-31'
) All_date
left join payment p on on date(p.invoice_date )=All_date.C_date
where C_date
BETWEEN '2017-08-01' AND '2018-08-01'
GROUP BY income_month ,month_name,income_year