0

I have payment data table (MySQL) to record all the payments. I want to group all the payments by date. Actually I want to group them by month to analyze what's the income they get for a specific month. If there are no payments in a specific month, I need that as 0.

Here is my SQL code for that.

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')

From this code, I get the following output :

enter image description here

I searched between '2018-01-01' AND '2018-08-01'. So there should be 7 months and 7 results. If there are no payments for month no 1 (January) , I want the sold_income = 0;

How do I do that ? Please help me....

Chanaka De Silva
  • 406
  • 1
  • 7
  • 21

1 Answers1

1

generate date and join with this your table and project your result

  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 
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63