我需要得到:
我该怎么写这样的查询?
select answer =
case sum(apples)%2
when 1 then 1
else 2
end
from fruits
如果总和为零,我需要第三个选项0 我的问题是sum(apples)%2在偶数和零情况下都返回0 感谢
答案 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