问题:
我正在尝试在包含使用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,但我根本无法使这些工作(所以我从问题中省略了它们以减少混淆我的原始(主要)问题。
答案 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 WHEN
或IIF
(SQL 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