Include missing months in Group By query

后端 未结 3 688
暗喜
暗喜 2020-12-06 11:17

I think I have a tough one here... :(

I am trying to get an order count by month, even when zero. Here\'s the problem query:

SELECT datename(month,          


        
3条回答
  •  無奈伤痛
    2020-12-06 11:36

    Here is one using recursive CTE:

    declare @StartDate datetime = '2015-04-01';
    declare @EndDate datetime = '2015-06-01';
    
    -- sample data
    declare @orders table (OrderNumber int, OrderDate datetime);
    insert into @orders
    select 11, '2015-04-02'
    union all
    select 12, '2015-04-03'
    union all
    select 13, '2015-05-03'
    ;
    
    -- recursive CTE
    with dates
    as (
        select @StartDate as reportMonth
        union all
        select dateadd(m, 1, reportMonth)
        from dates
        where reportMonth < @EndDate
        )
    select 
        reportMonth,
        Count = count(o.OrderNumber)
    from dates
    left outer join @orders as o 
        on o.OrderDate >= reportMonth
        and o.OrderDate < dateadd(MONTH, 1, reportMonth)
    group by 
        reportMonth
    option (maxrecursion 0);
    ;
    

提交回复
热议问题