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

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

First of all my result looks like this:

KONTONR Month SELSKAPSKODE BE
相关标签:
3条回答
  • 2021-01-21 11:38

    if you don't want to do all that you could also modify this: SUM(BELOP) with this: Sum (case when BELOP is not null then 1 else 0 end)

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-21 11:53

    You can also add in the year if you have a creation date for the interactions you are counting which may be helpful if your interactions span the course of many years.

    with Months(Month) as
    (
      select 1
      union all
      select Month + 1
      from Months
      where Month < 12
    )
    select M.Month, year(CreatedOn) as Year,
           count(amount) Count,
           isnull(sum(amount), 0) Sum
    from Months as M
      left outer join Charge as C
        on M.Month = (month(CreatedOn))
    group by M.Month, year(CreatedOn) order by year(CreatedOn)
    

    0 讨论(0)
提交回复
热议问题