-1

I have a table with the below mentioned schema:

InvoiceID int PK,
Date datetime,
Amount Money

I now create a table which contains the Year, Month and Amount from the table above.

Year | Month | Amount 
2014 | Dec   | 10

I then pivot this table with all the months

select * from (select year(Date) as InvoiceYear, isnull(left(datename(month, date),3),0) as InvoiceMonth, Amount from Invoice) as Sid pivot ( sum(Amount) for InvoiceMonth in (jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec)) as P1

The problem I have is that I need to set the months which don't have any amounts to zero instead of null

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Sid
  • 141
  • 3
  • 13

1 Answers1

1

When you have a month without an invoice it's always going to generate a null value for the amount in that month when you pivot the table.

If you don't want to set up a tally table suggested in comments, you can go with something like this - but it's worth nothing that tally tables usually have better performance.

SELECT 
 invoiceYear,
 isnull(jan,0) as [jan],
 isnull(feb,0) as [feb],
 etc...
 FROM
 (select * from 
(select year(Date) as InvoiceYear, 
isnull(left(datename(month, date),3),0) as InvoiceMonth,
 Amount from Invoice) 
 as Sid 
 pivot ( sum(Amount) for InvoiceMonth in (jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec)) as P1
 ) A
 GROUP BY invoiceYear
Jared_S
  • 166
  • 6