简体   繁体   English

案例表达

[英]Case expression

How do you write a case expression that has 2 conditions ?如何编写具有 2 个条件的 case 表达式?

What I'm trying to say in the code below is when the color is red and the quality is bad then price.我在下面的代码中要说的是当颜色是红色并且质量不好时价格。 And when color is red but quality is Good then price *2.当颜色为红色但质量良好时,价格 *2。

There's only 2 options for quality ie Good and Bad质量只有两种选择,即好和坏

Code Example:代码示例:

Case when color = 'red' and quality = 'Bad' then price
     else price * 2
end as RED

Here is the basic structure of a CASE:以下是 CASE 的基本结构:

case
    when A then X
    when B then Y
    else Z
end

You can have as many "when/then" lines as you want (or your dbms supports).您可以根据需要(或您的 dbms 支持)拥有尽可能多的“when/then”行。 You can put any boolean expression in place of A or B. You can put any expression in place of X, Y, and Z, including another CASE.您可以用任何布尔表达式代替 A 或 B。您可以用任何表达式代替 X、Y 和 Z,包括另一个 CASE。

So you could simply list out all your combinations like this:因此,您可以像这样简单地列出所有组合:

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

Or you can nest them like this:或者你可以像这样嵌套它们:

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

Considering your example:考虑到你的例子:

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

look at the syntax the case ... end can be used in differen ways.查看语法 case ... end 可以以不同的方式使用。

case field when value1 then result1 when value2 then result2 ... else result0 end

or或者

case when field=value1 then result1 when field=value2 then result2 ... else result0 end

each results (result1, result2, result0) may itself be a case ... end statement.每个结果(result1、result2、result0)本身可能是一个 case ... end 语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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