为什么这个SQL查询在执行时会返回NULL?
请参阅代码 - 提前致谢
代码:
SELECT
SUM(CONVERT(INT, Client_AmntApplied)) AS AmountApplied
FROM
ClientDatabase C
WHERE
DateReceivedMonth = 1
AND ADR1 = 2017
AND StepStatus IS NULL;
输出:
答案 0 :(得分:2)
显然,没有记录与where子句一起返回。
WHERE DateReceivedMonth = 1
AND ADR1 = 2017
AND StepStatus IS NULL;
检查您的where子句,如果您希望默认值为0
,请使用ISNULL
SELECT SUM(CONVERT(INT, ISNULL(Client_AmntApplied,0))) AS AmountApplied
FROM ClientDatabase C
WHERE DateReceivedMonth = 1
AND ADR1 = 2017
AND StepStatus IS NULL;
如果没有要返回的记录,并且您想要显示默认值,则可以使用COALESCE
SELECT COALESCE(SUM(CONVERT(INT, ISNULL(Client_AmntApplied,0))),0) AS AmountApplied
FROM ClientDatabase C
WHERE DateReceivedMonth = 1
AND ADR1 = 2017
AND StepStatus IS NULL;
答案 1 :(得分:1)
declare @ast varchar(10)
set @ast = null
SELECT SUM(CONVERT(INT, Client_AmntApplied)) AS AmountApplied
FROM ClientDatabase C
WHERE DateReceivedMonth = 1
AND ADR1 = 2017
and (StepStatus = ISNULL(@ast, StepStatus ) Or StepStatus is null)
除此之外,您还可以使用SUM(CONVERT(INT, ISNULL(Client_AmntApplied,0)))
试试这种方式
答案 2 :(得分:1)
关于SUM的事实:
NULL
(WHERE条件与任何记录不匹配或表格为空)NULL
值(因此COALESCE(column, 0)
ISNULL(column, 0)
对结果没有影响)NULL
NULL
如果您想要在没有要汇总的记录时得到0而不是NULL
,则可以使用以下表达式之一:
COALESCE(SUM(column), 0) AS columnSum
-- or --
ISNULL(SUM(column), 0) AS columnSum
或者CASE..WHEN
构造(COALESCE
只是一个简写)。
检查查询结果而不进行聚合,以检查是否有与WHERE条件匹配的记录。