在MS SQL中使用PIVOT时如何使用ISNULL或COALESCE函数

时间:2014-12-09 17:30:49

标签: sql sql-server tsql pivot isnull

我有一个包含下面提到的架构的表:

InvoiceID int PK,
Date datetime,
Amount Money

我现在创建一个表格,其中包含上表中的年,月和金额。

Year | Month | Amount 
2014 | Dec   | 10

然后我将这个表与所有月份一起转动

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

我遇到的问题是我需要设置没有任何金额而不是零的月份

1 个答案:

答案 0 :(得分:1)

如果您有一个没有发票的月份,那么当您转动表格时,它总是会为该月份的金额生成空值。

如果你不想设置评论中建议的理货表,你可以选择这样的东西 - 但是理货表通常具有更好的性能并不值得。

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