检查列值是否为零MS SQL Server

时间:2016-10-25 08:32:52

标签: sql sql-server tsql

我有一个视图,它有一个复杂的CASE语句来确定其中一列的值。

SELECT a.itemcode, count(*) total, b.foo
    CASE 
    WHEN foo IN ('aab', 'aac')
    THEN 1
    WHEN foo IN ('qqq', 'fff')
    THEN 2
    WHEN foo IN ('foo', 'bar')
    THEN 10 % count(*)
    ELSE 9 % count(*)
    END AS other_total

FROM a INNER JOIN b ON a.itemcode = b.itemcode
GROUP BY itemcode, foo

我想添加一个对other_total列的值的检查。如果是0,我想将值设置为1

显然,我可以在CASE陈述中包围整个事情......

CASE ( CASE 
    WHEN foo IN ('aab', 'aac')
    THEN 1
    WHEN foo IN ('qqq', 'fff')
    THEN 2
    WHEN foo IN ('foo', 'bar')
    THEN 10 % count(*)
    ELSE 9 % count(*)
    END )
WHEN 0 THEN 1
ELSE  CASE 
    WHEN foo IN ('aab', 'aac')
    THEN 1
    WHEN foo IN ('qqq', 'fff')
    THEN 2
    WHEN foo IN ('foo', 'bar')
    THEN 10 % count(*)
    ELSE 9 % count(*)
    END
END AS other_total

但这有点乱,似乎应该有一个更简单的方法。

是否有另一个函数,类似于ISNULL(),如果它等于零,我可以更改列的值吗?

ANSWER

感谢gofr1的答案,我能够解决这个问题。如果case语句等于0,我使用NULLIF函数返回NULL,然后用ISNULL函数包围,如果NULLIF函数返回NULL,则将值设置为1。

SELECT a.itemcode, count(*) total, b.foo,
    ISNULL (
        NULLIF (
            CASE 
            WHEN foo IN ('aab', 'aac')
            THEN 1
            WHEN foo IN ('qqq', 'fff')
            THEN 2
            WHEN foo IN ('foo', 'bar')
            THEN 10 % count(*)
            ELSE 9 % count(*)
            END 
        ), 0)
    ), 1) other_total

FROM a INNER JOIN b ON a.itemcode = b.itemcode
GROUP BY itemcode, foo

3 个答案:

答案 0 :(得分:2)

SELECT NullIf(<your_code>, 0) AS zero_to_null
     , Coalesce(NullIf(<your_code>, 0), 1) AS zero_to_null_to_one

SELECT CASE WHEN other_total = 0 THEN 1 ELSE other_total END AS new_total
FROM   (
        <your_code>
       ) AS a_subquery

答案 1 :(得分:1)

您可以使用NULLIF

  

如果两个指定的表达式相等,则返回null值。

CASE WHEN 
NULLIF(
    CASE WHEN foo IN ('aab', 'aac') THEN 1
        WHEN foo IN ('qqq', 'fff') THEN 2
        WHEN foo IN ('foo', 'bar') THEN 10 % count(*)
        ELSE 9 % count(*)
        END
    ,0) IS NULL THEN 0 ELSE 1 END
 AS other_total

如果值为= 0,则它变为NULL,否则该值将在输出中。然后我们使用CASE WHEN value IS NULL then 0 else 1

答案 2 :(得分:0)

使用DERIVED QUERY或CTE

- 派生查询

SELECT itemcode, total, foo, case when other_total = 0 then 1 else other_total end as other_total
FROM
(
  SELECT a.itemcode, count(*) total, b.foo
      CASE 
      WHEN foo IN ('aab', 'aac')
      THEN 1
      WHEN foo IN ('qqq', 'fff')
      THEN 2
      WHEN foo IN ('foo', 'bar')
      THEN 10 % count(*)
      ELSE 9 % count(*)
      END AS other_total

  FROM a INNER JOIN b ON a.itemcode = b.itemcode
  GROUP BY itemcode, foo
) d

OR

你可以在CASE WHEN的最后2个表达式上使用CASE ...因为这是唯一可以给你0的地方。

  WHEN foo IN ('foo', 'bar')
  THEN CASE WHEN 10 % count(*) = 0 THEN 1 ELSE 10 % count(*) END
  ELSE CASE WHEN  9 % count(*) = 0 THEN 1 ELSE  9 % count(*) END
  END AS other_total