0

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

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'

我在考虑计数应该返回的空白数据。但我根本没有得到任何结果。请指导我做错了什么以及我应该怎么做才能使所有计数值为零而不是空白。

4

3 回答 3

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
于 2013-09-19T05:39:59.647 回答
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'
于 2013-09-19T03:32:12.560 回答
0

我希望count()返回 0。如果没有,您可以尝试使用coalesce()

coalesce([405], 0) as [405]
于 2013-09-19T03:21:56.330 回答