[英]Case expression
如何編寫具有 2 個條件的 case 表達式?
我在下面的代碼中要說的是當顏色是紅色並且質量不好時價格。 當顏色為紅色但質量良好時,價格 *2。
質量只有兩種選擇,即好和壞
代碼示例:
Case when color = 'red' and quality = 'Bad' then price
else price * 2
end as RED
以下是 CASE 的基本結構:
case
when A then X
when B then Y
else Z
end
您可以根據需要(或您的 dbms 支持)擁有盡可能多的“when/then”行。 您可以用任何布爾表達式代替 A 或 B。您可以用任何表達式代替 X、Y 和 Z,包括另一個 CASE。
因此,您可以像這樣簡單地列出所有組合:
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
考慮到你的例子:
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 ... end 可以以不同的方式使用。
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)本身可能是一個 case ... end 語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.