用于检查总和是偶数,奇数还是零的mssql查询?

时间:2014-02-06 20:42:56

标签: sql-server

我需要得到:

  • 0如果sum(apples)为0
  • 1如果sum(apples)是奇数
  • 2如果总和(苹果)是 甚至

我该怎么写这样的查询?

    select answer = 
      case sum(apples)%2
         when 1 then 1
         else 2 
      end
    from fruits

如果总和为零,我需要第三个选项0 我的问题是sum(apples)%2在偶数和零情况下都返回0 感谢

3 个答案:

答案 0 :(得分:1)

您需要按以下方式更改查询。

   select answer = 
      case 
          WHEN sum(apples)=0 then 0
          WHEN sum(apples)%2 = 1 then 1
         else 2 
      end
    from fruits

根据MySQL Documentation您有两种语法选项,您只需要更改为第二个选项

CASE case_value
    WHEN when_value THEN statement_list
    [WHEN when_value THEN statement_list] ...
    [ELSE statement_list]
END CASE

CASE
    WHEN search_condition THEN statement_list
    [WHEN search_condition THEN statement_list] ...
    [ELSE statement_list
END CASE    

答案 1 :(得分:0)

您可以按照自己想要的方式使用这一小段代码......

declare @n int = 0
select case @n when 0 then 'zero' else (case (@n%2) when 1 then 'odd' else 'even' end) end

尝试使用@n。

的其他值

答案 2 :(得分:0)

根据apples列的定义方式(它是强制性的,或允许NULL s),SUM可能会返回非NULL 或者它可以返回NULL:

SELECT  x.OrderID,
        SUM(x.Qty) AS SumOfQty,
        CASE 
            WHEN SUM(x.Qty) = 0 THEN 0
            WHEN SUM(x.Qty) % 2 = 1 THEN 1
            WHEN SUM(x.Qty) % 2 = 0 THEN 2
            ELSE -1 -- SUM(x.Qty) IS NULL
        END AS CaseSumOfQty
FROM (
    SELECT 1, 100 UNION ALL 
    SELECT 2, 200 UNION ALL 
    SELECT 2, 301 UNION ALL 
    SELECT 3, 0   UNION ALL 
    SELECT 4, NULL
) x(OrderID, Qty)
GROUP BY x.OrderID;

输出:

OrderID SumOfQty    CaseSumOfQty
------- ----------- ------------
1       100         2
2       501         1
3       0           0
4       NULL        -1 -- SUM(x.Qty) IS NULL