繁体   English   中英

案例表达

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM