2

试图弄清楚如何在 T-SQL 的 case 语句中合并 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
4

2 回答 2

3

您可以使用OR这种方式:

COUNT(Case 
        When (car.[Weight] IS null) or (car.BinNumber is null)
        then 0 
        else car.CarKey End) as Carkey
于 2012-09-26T19:26:45.287 回答
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
于 2012-09-26T19:32:09.457 回答