在使用SUM的SQL查询中处理NULL值

时间:2015-11-11 15:15:55

标签: sql excel vba excel-vba

问题:

我正在尝试在包含使用SUM的计算的VBA(Excel)中执行查询,例如

Select SUM(field1) - SUM(field2) as 'newField' from y

如果没有空值或空字段,那么代码可以正常工作,但是只要在field1或field2中有一个空/空值,就会返回一个空白。

因此,如果SUM(field1) = 17 and SUM(field2) = null我想看到查询返回17而不是空值。

守则:

Public Function GetRiskRecords(ByVal strPrgNo As String) As Variant

Dim strSQL As String

strSQL = "Select [tblRiskMitigating$].RiskID, [tblRiskMitigating$].Program_No, [tblRiskMain$].RiskID, [tblRiskMain$].Program_No, [tblRiskMain$].Department, [tblRiskMain$].DateAdded, [tblRiskMain$].OwnerID, [tblRiskMain$].Description, " _
        & " [tblRiskMain$].RiskTo, [tblRiskMain$].Probability, " _
        & " Sum([tblRiskMain$].ScheduleImpact) - Sum([tblRiskMitigating$].ScheduleReduction) as 'NewScheduleImpact', " _
        & " Sum([tblRiskMain$].CostImpact) - Sum([tblRiskMitigating$].CostReduction) as 'NewCostImpact'" _
        & " From [tblRiskMain$]" _
        & " Left Join [tblRiskMitigating$] on [tblRiskMain$].RiskID = [tblRiskMitigating$].RiskID AND [tblRiskMain$].Program_No = [tblRiskMitigating$].Program_No" _
        & " Where [tblRiskMain$].Program_No = '" & strPrgNo & "'" _
        & " Group By [tblRiskMitigating$].RiskID, [tblRiskMitigating$].Program_No, [tblRiskMain$].RiskID, [tblRiskMain$].Program_No, [tblRiskMain$].Department, [tblRiskMain$].DateAdded, [tblRiskMain$].OwnerID, [tblRiskMain$].Description, " _
        & " [tblRiskMain$].RiskTo, [tblRiskMain$].Probability"

Call Open_Conn(strDb)
Call Open_RS(strSQL)

If rs.EOF Then
    Debug.Print ("Error: no records")
Else
    GetRiskRecords = rs.GetRows
End If

Call Close_RS
Call Close_Conn

End Function

背景:

我已经做了一些挖掘并尝试在开始时添加isnull和iif,但我根本无法使这些工作(所以我从问题中省略了它们以减少混淆我的原始(主要)问题。

1 个答案:

答案 0 :(得分:3)

您可以使用ISNULL/COALESCE

Select SUM(ISNULL(field1,0)) - SUM(ISNULL(field2,0)) as 'newField' 
from y;

甚至合并为一个SUM

Select SUM(ISNULL(field1,0) - ISNULL(field2,0)) as 'newField' 
from y;

如果ISNULL/COALESCE可以与CASE WHENIIFSQL Server 2012+)轻松互换:

CASE WHEN field1 IS NULL THEN 0
     ELSE field1
END;

IIF(field1 IS NULL, 0, field1);

修改

以上代码以SQL Server为导向,对于EXCEL,您应该使用:

SELECT SUM(IIF(field1 IS NULL, 0, field1) - IIF(field2 IS NULL, 0 field2)) 
FROM y