SQL在Pivot中用0替换Null值

时间:2014-06-19 18:17:38

标签: sql sql-server

我有这个查询,

Select * From 
(Select 
    S.EmployeeID As [Employee ID],
    E.Name,
    YEAR([Date]) As [Year],
    DATENAME(MONTH, [Date]) As [Month], 
    IsNull(SUM(Amount), 0) As TotalAmount
    From Sales S Left Outer Join Employee E
    On S.EmployeeID = E.EmployeeID
    Group By 
    S.EmployeeID,
    E.Name, 
    YEAR([Date]),
    DATENAME(MONTH, [Date])) As MonthlySale
Pivot(SUM(TotalAmount)   
    For Month In ([January],[February],[March],[April],[May],
                  [June],[July],[August],[September],[October],
                  [November],[December])) As MyPivot

返回此表(示例表),

+--+---------+-----+------+-------+
|ID|  Name   |Year |Jan   |Feb    | Exc
+--+---------+-----+------+-------+
|1 |John Doe |2014 |Null  |Null   | Exc
+--+---------+-----+------+-------+
|2 |Jane Doe |2014 |Null  |Null   | Exc
+--+---------+-----+------+-------+

如何将这些空值更改为0,我尝试过IsNull,但没有任何想法,任何想法?

2 个答案:

答案 0 :(得分:1)

结束使用,

Select [Employee ID], Name, @Year As [Year],
IsNull(January, 0)  As January,  IsNull(February, 0)  As February,  IsNull(March, 0)      As March,
IsNull(April, 0)    As April,    IsNull(May, 0)       As May,       IsNull(June, 0)       As June,
IsNull(July, 0)     As July,     IsNull(August, 0)    As August,    IsNull(September, 0)  As September,
IsNull(October, 0)  As October,  IsNull(November, 0)  As November,  IsNull(December, 0)   As December
From 

答案 1 :(得分:0)

with cte as 
(

Select * From 
(Select 
    S.EmployeeID As [Employee ID],
    E.Name,
    YEAR([Date]) As [Year],
    DATENAME(MONTH, [Date]) As [Month], 
    IsNull(SUM(Amount), 0) As TotalAmount
    From Sales S Left Outer Join Employee E
    On S.EmployeeID = E.EmployeeID
    Group By 
    S.EmployeeID,
    E.Name, 
    YEAR([Date]),
    DATENAME(MONTH, [Date])) As MonthlySale
Pivot(SUM(TotalAmount)   
    For Month In ([January],[February],[March],[April],[May],
                  [June],[July],[August],[September],[October],
                  [November],[December])) As MyPivot

)
select *, coalesce(Januar, 0) from cte