空数据的SQL数据透视表

时间:2013-09-19 03:12:33

标签: sql sql-server sql-server-2008 pivot

以下是我的查询以生成透视结果:

SELECT '# of Corrective Actions open and overdue' as [Corrective Actions breakdown], 
[405],
[2865],
[3142],
[405]+[2865]+[3142] as [Total]
FROM
(Select il.Locationid , ca.CorrectiveActionsid, il.locOrder, ca.isDeleted caDeleted, i.isDeleted iDeleted, i.CompanyId companyid,ca.CADateBy, ca.Status  from IncidentLocation il inner join incident i on il.IncidentId = i.IncidentId 
inner join CorrectiveActions ca on i.IncidentId = ca.IncidentId  
) AS SourceTable
PIVOT
(
COUNT(CorrectiveActionsid)
FOR LocationId IN ([405],[2865],[3142])
) PivotTable 

where locOrder = 0 and caDeleted =0 and iDeleted = 0 and companyId = 210
and CADateBy <= '2013-01-01'  and [Status] = 'Open'

我在考虑空白数据,计数应该返回o。但我一点也没有结果。请指导我做错了什么,我该怎么办才能得到零而不是空白所有计算值。

3 个答案:

答案 0 :(得分:1)

看起来你的查询没有返回任何行,你可以像这样修复它(我没有修复查询的其他部分,只是想给你一个解决方法):

select
    A.[Corrective Actions breakdown],
    coalesce([405], 0) as [405],
    coalesce([2865], 0) as [2865],
    coalesce([3142], 0) as [3142],
    coalesce([405], 0) + coalesce([2865], 0) + coalesce([3142], 0) as [Total]
from (select '# of Corrective Actions open and overdue' as [Corrective Actions breakdown]) as A
    outer apply (
   SELECT
        [405],
        [2865],
        [3142]
   FROM
        (Select il.Locationid , ISNULL(ca.CorrectiveActionsid, 0) AS CorrectiveActionsid, il.locOrder, ca.isDeleted caDeleted, i.isDeleted iDeleted, i.CompanyId companyid,ca.CADateBy, ca.Status  from IncidentLocation il inner join incident i on il.IncidentId = i.IncidentId 
        inner join CorrectiveActions ca on i.IncidentId = ca.IncidentId  
        ) AS SourceTable
   PIVOT
        (
        COUNT(CorrectiveActionsid)
        FOR LocationId IN ([405],[2865],[3142])
        ) PivotTable 
        where locOrder = 0 and caDeleted =0 and iDeleted = 0 and companyId = 210
    and CADateBy <= '2013-01-01'  and [Status] = 'Open'
    ) as p

答案 1 :(得分:0)

我希望count()返回0.如果不是,您可以尝试使用coalesce()

coalesce([405], 0) as [405]

答案 2 :(得分:0)

在SQL Server中,COUNT将忽略NULL值。话虽这么说,在要聚合的列上使用ISNULL函数。

   SELECT '# of Corrective Actions open and overdue' as [Corrective Actions breakdown], 
        [405],
        [2865],
        [3142],
        [405]+[2865]+[3142] as [Total]
   FROM
        (Select il.Locationid , ISNULL(ca.CorrectiveActionsid, 0) AS CorrectiveActionsid, il.locOrder, ca.isDeleted caDeleted, i.isDeleted iDeleted, i.CompanyId companyid,ca.CADateBy, ca.Status  from IncidentLocation il inner join incident i on il.IncidentId = i.IncidentId 
        inner join CorrectiveActions ca on i.IncidentId = ca.IncidentId  
        ) AS SourceTable
   PIVOT
        (
        COUNT(CorrectiveActionsid)
        FOR LocationId IN ([405],[2865],[3142])
        ) PivotTable 

   where locOrder = 0 and caDeleted =0 and iDeleted = 0 and companyId = 210
        and CADateBy <= '2013-01-01'  and [Status] = 'Open'