SQL How to show '0' value for a month, if no data exists in the table for that month

后端 未结 3 1818
天涯浪人
天涯浪人 2021-01-21 10:55

First of all my result looks like this:

KONTONR Month SELSKAPSKODE BE
3条回答
  •  清酒与你
    2021-01-21 11:50

    You can query a table with the values 1-12 and left outer join your result.

    Here is a sample using a table variable instead of your query and a CTE to build a table with numbers.

    declare @T table
    (
      Month int
    )
    
    insert into @T values(1)
    insert into @T values(1)
    insert into @T values(1)
    insert into @T values(3)
    insert into @T values(3)
    
    ;with Months(Month) as
    (
      select 1
      union all
      select Month + 1
      from Months
      where Month < 12
    )
    select M.Month,
           count(T.Month) Count,
           isnull(sum(T.Month), 0) Sum
    from Months as M
      left outer join @T as T
        on M.Month = T.Month
    group by M.Month
    

    Result:

    Month       Count       Sum
    ----------- ----------- -----------
    1           3           3
    2           0           0
    3           2           6
    4           0           0
    5           0           0
    6           0           0
    7           0           0
    8           0           0
    9           0           0
    10          0           0
    11          0           0
    12          0           0
    

提交回复
热议问题