generate empty rows even if empty between 2 dates

后端 未结 3 1682
不思量自难忘°
不思量自难忘° 2021-01-20 02:01

I have this simple query that fetches all completed orders between 2 dates(about 6 months at a time):

select IFNULL(sum(o.amount), 0) as amount, o.completed_         


        
相关标签:
3条回答
  • 2021-01-20 02:27

    Here is what you need:

    1] create an auxiliary table

     create table db.myDates(
       completed_at date not null
     )
    

    2] fill the table with the months in range, for example:

     insert into db.myDates values('2011-10-01'),
     ('2011-11-01'),
     ('2011-12-01'),
     ('2012-01-01'),
     ('2012-02-01'),
     ('2012-03-01');
    

    3] then select:

     select a.completed_at, sum(b.amount)
     from myDates a
     left join orders b 
       on extract(year_month from a.completed_at)=extract(year_month from b.completed_at)
         and date(b.completed_at) between '2012-01-05' and '2012-06-05'
     group by year(b.completed_at)), month(dateCompleted)
     order by a.completed_at;
    

    the result looks like this (dates mine)

    2012-01-01  27
    2012-02-01  NULL
    2012-03-01  47
    2012-04-01  13
    2012-05-01  12
    2012-06-01  15
    
    0 讨论(0)
  • This query is complicated due to a number of factors.

    The easiest solution might be to add a 0 amount on the first of each month.

    0 讨论(0)
  • 2021-01-20 02:39

    Try with coalesce function which will return '0' if the sum(orders.amount) is null for a specific month:

    select COALESCE(sum(o.amount), 0) as amount, o.completed_at 
    from orders o 
    where date(o.completed_at) between '2011/10/01' and '2012/03/06' 
    group by year(o.completed_at), month(o.completed_at) order by o.completed_at
    
    0 讨论(0)
提交回复
热议问题