删除NULL时的CASE逻辑

时间:2015-08-27 13:57:38

标签: sql sql-server sql-server-2012

这是我的第一篇文章,我试图彻底搜索这个问题,所以如果已多次在其他地方发布,请接受我的道歉,但我想知道是否有人遇到过以下问题尝试从结果集中删除NULL:

case Occurrence
    when NULL then '0'
    else occurrence
    end as Occurrence,
case Aggregate
    when NULL then '0'
    else Aggregate
    end as Aggregate,

这对我的NULL没有任何作用;然而,这就是诀窍:

case 
    when occurrence is NULL then '0'
    else occurrence
    end as Occurrence,
case 
    when aggregate is NULL then '0'
    else Aggregate
    end as Aggregate

有没有人知道为什么这样做?我正在使用SQLServer2012。

我也不是很熟悉编程,只有不到一年的SQL经验。

谢谢!

3 个答案:

答案 0 :(得分:3)

您应该使用ISNULL()或COALESCE()系统函数来处理空值

类似

SELECT ISNULL(Occurrence , 0) AS Occurrence
      ,ISNULL(Aggregate  , 0) AS Aggregate
FROM Table

OR

SELECT COALESCE(Occurrence , 0) AS Occurrence
      ,COALESCE(Aggregate  , 0) AS Aggregate
FROM Table

使用

在案例陈述中无效的原因
case Occurrence
    when NULL then '0'
    else occurrence
    end as Occurrence,

是因为它将其解释为

CASE
WHEN Occurrence = NULL THEN 0
    ELSE Occurrence 
END

如果您使用null =,<> null的任何其他运算符,则使用IS NULLIS NOT NULL在sql server中检查Null或<,<它产生NULL,因此产生了意想不到的结果。

仅适用于SQL Server 2012及更高版本

在sql server 2012及更高版本中,您还拥有IIF功能

SELECT IIF(Occurrence IS NULL, 0, Occurrence) AS Occurrence
      ,IFF(Aggregate IS NULL , 0, Aggregate)  AS Aggregate
FROM Table

答案 1 :(得分:2)

您使用simple case

  

简单的CASE表达式通过将第一个表达式与每个WHEN子句中的表达式进行比较来进行等效。如果这些表达式是等价的,则返回THEN子句中的表达式。

     

允许仅进行相等检查

case Occurrence
    when NULL then '0'
    else occurrence
end as Occurrence,

执行如下:

case 
   when occurence = NULL then '0'
   else occurrence
end as Occurrence

然后表达式occurence = NULL返回NULL并被视为,如False

第二个案例使用完整条件的搜索CASE并且工作正常:

case 
  when occurrence IS NULL then '0'
  else occurrence
end as Occurrence,

所以你的问题是差异列IS NULL vs column = NULL

答案 2 :(得分:1)

尝试

select 1 where null =null
select 1 where null is null

你的陈述看起来像null等于null

select case when null is null then 1 else 0 end

select case null when null then 1 else 0 end

在您使用ISNULL的情况下,这将为您提供结果

SELECT ISNULL(null,1)