根据value_condition的计算结果,灵活地返回不同的result值。

命令格式

MaxCompute提供以下两种case when格式:
  • case <value>
    when <value1> then <result1>
    when <value2> then <result2>
    ...
    else <resultn>
    end
  • case
    when (<_condition1>) then <result1>
    when (<_condition2>) then <result2>
    when (<_condition3>) then <result3>
    ...
    else <resultn>
    end

参数说明

  • value:必填。比较的值。
  • _condition:必填。指定判断条件。
  • result:必填。返回值。

返回值说明

  • 如果result类型只有BIGINT、DOUBLE,统一转为DOUBLE后,再返回结果。
  • 如果result类型中有STRING类型,则统一转为STRING后,再返回结果。如果无法进行类型转换,例如BOOLEAN类型无法转换为STRING类型,则会返回报错。
  • 不允许其他类型之间的转换。

使用示例

例如表sale_detail的字段为shop_name string, customer_id string, total_price double,,包含数据如下。
+------------+-------------+-------------+------------+------------+
| shop_name  | customer_id | total_price | sale_date  | region     |
+------------+-------------+-------------+------------+------------+
| s1         | c1          | 100.1       | 2013       | china      |
| s2         | c2          | 100.2       | 2013       | china      |
| s3         | c3          | 100.3       | 2013       | china      |
| null       | c5          | NULL        | 2014       | shanghai   |
| s6         | c6          | 100.4       | 2014       | shanghai   |
| s7         | c7          | 100.5       | 2014       | shanghai   |
+------------+-------------+-------------+------------+------------+
命令示例如下。
select 
case  
when region='china' then 'default_region'
when region like 'shang%' then 'sh_region'
end as region 
from sale_detail;
返回结果如下。
+------------+
| region     |
+------------+
| default_region |
| default_region |
| default_region |
| sh_region  |
| sh_region  |
| sh_region  |
+------------+