ISNULL()不工作......可能是错误的放置?

时间:2012-06-06 15:31:44

标签: sql isnull

以下查询在其外部效果很好仍然会将空值返回为NULL而不是0。具体来说,这是对在指定日期范围内发生事件的次数进行总结。如果参数中的值不存在(即NULL),那么为了便于阅读,我希望它返回一个0(表,它是多个临时表的连接,只包含整数。我已经研究并发现了这个案例“How can I change NULL to 0 when getting a single value from a SQL function?”,并尝试了所有的建议,包括COALESCE

(SELECT tn.teamtext, tn.teamid, ISNULL(sum(ISNULL(case when CONVERT(smalldatetime,ca.dModLast,101) BETWEEN '2012-03-01' AND '2012-03-10' then 1 else 0 end, 0)), 0) AS cnt3
  FROM teamnames AS tn 
    LEFT OUTER JOIN caseaudit AS ca
    ON tn.teamID = ca.referteamID2
  WHERE ca.referteamid1 <> ca.referteamid2 AND ca.isactive = 1 AND ca.groupid = 18 AND ca.accountid = 2 AND ca.referteamid1 = 31 AND ca.auditnote <> 'Suspend Case'
  GROUP BY tn.teamtext, tn.teamid) AS c

要了解我正在查看的返回表,这里是:

4H BOSS                    55   59  3
4H BSG                     0    3   2
4H SALES AND MKTG          0    0   0
ACCOUNTS RECEIVABLE        0    0   0
ASSET MANAGEMENT           9    16  0
AUDIT                      0    0   NULL
BOSS                       4    5   0
CORPORATE BSG              0    7   5
CUSTOMER SUPPORT           87   133 NULL
NETWORK ENGINEERING        11   15  0
PRODUCTION ENGINEERING     116  142 5
PRODUCTION OPERATIONS      0    1   0
SECURITY                   2    6   3
SNFAL PRODUCT TEAM         0    14  11
VOICE SERVICES             18   21  0
XEROX                      4    8   0

3 个答案:

答案 0 :(得分:2)

我同意(到目前为止)另外两个响应 - 此查询中的NULL逻辑应该像你说的那样工作。但...

我在本地表上运行了类似你的查询,一切运行正常。然后我添加了最外面的parens:

(SELECT...
 ...) AS c

并出现错误,因为SQL不支持该格式。这个,结合你的示例显示四个列,其中只有三个列在查询中,这使我强烈怀疑这是一个更大的查询中的子查询...在这种情况下,null / not null问题可能纠结在完整查询的逻辑,而不仅仅是这个子查询。如果我的推测是正确的,请发布完整的查询以供我们考虑。

答案 1 :(得分:1)

我假设,因为CONVERT(smalldatetime,dModLast,101) BETWEEN '2012-03-01' AND '2012-03-10'引用了正确的表,有时它可以计算为NULL并且案例没有得到它。

您可以尝试明确执行when (dModLast is null) then 0

编辑:

case
   when dModLast is null then 0
   when CONVERT(smalldatetime,dModLast,101) BETWEEN '2012-03-01' AND '2012-03-10' then 1 
   else 0 
end 

答案 2 :(得分:1)

更改为

ISNULL(SUM(CASE WHEN ISNULL(ca.dModLast,0)=0 THEN 0 ELSE CASE WHEN CONVERT(smalldatetime,ca.dModLast,101) BETWEEN '2012-03-01' AND '2012-03-10' THEN 1 ELSE 0 END END),0) as cnt3