Sqlserver
 SQL >> Database >  >> RDS >> Sqlserver

Mostrare 0 per mesi senza dati in SQL Server

Il trucco è partire da una tabella di numeri da 1 a 12 e fare left join sui dati reali, così i mesi vuoti appaiono con zero. Esempio con variabile tabella e CTE:

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

Risultato: ogni mese appare e ISNULL trasforma gli aggregati vuoti in zero.