Include missing months in Group By query

后端 未结 3 696
暗喜
暗喜 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 11:41

    Since your query Just Can't guess the months you want, you will need to have the Months that you want stored in somewhere, Join them with your table, and then group. Something like:

    ;With Months (Month) 
    AS
    (
    
        select 'January' as Month
        UNION
        select 'February' as Month
        UNION
        select 'March' as Month
        UNION
        select 'April' as Month
        UNION
        select 'May' as Month
        UNION
        select 'June' as Month
        UNION
        select 'July' as Month
        UNION
        select 'August' as Month
        UNION
        select 'September' as Month
        UNION
        select 'October' as Month
        UNION
        select 'November' as Month
        UNION
        select 'December' as Month
    
    )
    --Also you could have them in a "Months" Table
    

    Then Just JOIN this table with your table:

       Select 
        SELECT datename(month, OrderDate) as Month, COUNT(OrderNumber) 
        FROM Months T1
        LEFT JOIN OrderTable T2 on datename(month, T2.OrderDate) = T2.Month
        WHERE (T2.OrderDate >= '2012-01-01' and T2.OrderDate <= '2012-06-30') 
    OR T2.OrderDate IS NULL --So will show you the months with no rows
        GROUP BY year(T2.OrderDate), month(T2.OrderDate), datename(month, T2.OrderDate)
    

    Hope it works!

提交回复
热议问题