Group by month including empty months

后端 未结 2 891
失恋的感觉
失恋的感觉 2020-12-21 00:20

I want to select all my order values per month. I know this works fine with GROUP BY month but only with months with orders in it. Now I want also the months with no orders

2条回答
  •  悲哀的现实
    2020-12-21 00:49

    After searching for a simple solution i finally found this which I think is SIMPLE. This will show last year and this years sales side by side.

    select 
           date_format(current_date - INTERVAL 1 YEAR,'%Y') as LAST_YR,
           date_format(NOW(),'%Y') as THIS_YR,
           monthname(date) as month,
           sum(case when year(date) = date_format(current_date - INTERVAL 1 YEAR,'%Y') then amount else 0 end) as sales_ly,
           sum(case when year(date) = DATE_FORMAT(NOW(),'%Y') then amount else 0 end) as sales_ty
    from tablename
    where date between date_format(current_date - INTERVAL 1 YEAR,'%Y-%01-%01')
    and date_format(current_date, '%Y-%12-%31')
    group by monthname(date)
    order by max(month(date));
    

提交回复
热议问题