或者在Case声明中

时间:2012-09-26 19:23:57

标签: tsql

试图弄清楚如何在T-SQL

的案例陈述中加入OR

我实际上是在检查两件事,如果其中任何一件都是真的,那么只需将它们视为0即可。

COUNT(Case When (car[Weight] IS null) then 0 else car.CarKey 
           OR When (car.BinNumber is null) then 0 else car.CarKey 
      End) as Carkey

也试过了,但语法错误

COUNT(Case When (car[Weight] IS null) then 0 
         else When (car.BinNumber is null) then 0 
         else car.CarKey 
      End) as Carkey

2 个答案:

答案 0 :(得分:3)

您可以这样使用OR

COUNT(Case 
        When (car.[Weight] IS null) or (car.BinNumber is null)
        then 0 
        else car.CarKey End) as Carkey

答案 1 :(得分:1)

您第二次尝试即将结束,只需删除一个else

COUNT(Case When (car[Weight] IS null) then 0 
     When (car.BinNumber is null) then 0 
     else car.CarKey 
  End) as Carkey

注意:如果要计算没有空值的项目,则不会这样做。零值仍然是一个值,因此它也将被计算。对于您不想计算的项目,请使用null

COUNT(Case When (car[Weight] IS null) then null 
     When (car.BinNumber is null) then null 
     else car.CarKey 
  End) as Carkey

或者改为使用sum

SUM(Case When (car[Weight] IS null) then 0 
     When (car.BinNumber is null) then 0 
     else 1
  End) as Carkey