如何编写具有两个条件的case表达式?
在下面的代码中,我想说的是,当颜色是红色的,质量是差的,那么价格。当颜色是红色但质量是好的,那么价格*2。
质量只有两种选择,即好的和坏的
代码示例:
Case when color = 'red' and quality = 'Bad' then price
else price * 2
end as RED发布于 2022-06-23 19:12:26
以下是案件的基本结构:
case
when A then X
when B then Y
else Z
end您可以拥有任意多行的“when/然后”行(或者dbms支持的行)。你可以用任何布尔表达式代替A或B。你可以用任何表达式来代替X,Y和Z,包括另一种情况。
因此,您可以简单地列出如下所有的组合:
case
when color = 'red' and quality = 'Good' then price*2
when color = 'red' and quality = 'Bad' then price
when color = 'blue' and quality = 'Good' then price*3
when color = 'blue' and quality = 'Bad' then price/2
else null
end as price或者你可以这样筑巢:
case
when color = 'red' then
case
when quality = 'Good' then price*2
else price
end
when color = 'blue' then
case
when quality = 'Good' then price*3
else price/2
end
else
null
end as price发布于 2022-06-23 15:55:04
考虑到你的例子:
select case color
when 'red'
then (case quality when 'Bad' then price when 'Good' then price*2 end)
when 'white'
then (case quality when 'Bad' then price+10 when 'Good' then (price+10)*2 end)
-- [... other conditions ...]
else 0
end as Price看看这个案子的语法..。末端可以用不同的方式使用。
case field when value1 then result1 when value2 then result2 ... else result0 end或
case when field=value1 then result1 when field=value2 then result2 ... else result0 end每个结果(result1,result2,result0)本身都可能是.结束陈述。
https://stackoverflow.com/questions/72732766
复制相似问题