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

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

First of all my result looks like this:

KONTONR Month SELSKAPSKODE BE
3条回答
  •  傲寒
    傲寒 (楼主)
    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)
    

提交回复
热议问题