case when的用法,列转行
表test,字段如图:
第一章、对表中字段可能出现的值,作出对应的处理
对单价与商品字段的值进行处理
1、将单价字段值为1的处理转换为不贵(case 单价 when 1 then ‘不贵’),
2、其余字段值转换处理为贵(else ‘贵’),
3、结束后单独列为一个字段贵不贵(end as 贵不贵)。
select
单价,
商品,
case 单价
when 1 then '不贵'
else '贵' end as 贵不贵,
case 单价
when 1 then '好吃'
when 10 then '一般'
else '苹果难吃' end as 好吃吗
from test;
第二段case when同理
注意:case后面跟列名
结果如图:
第二章、对表中字段可能出现的值,做出条件判断,再做出对应的处理
将商品字段值不为橘子且不为苹果的,处理转换为不贵(case when 商品<>‘橘子’ && 商品<>'苹果’then ‘不贵’),
其余字段值转换处理为贵(else ‘贵’),
结束后单独列为一个字段贵不贵(end as 贵不贵)**
注意:case后面不跟列名
select
单价,
商品,
case
when 商品<>'橘子' && 商品<>'苹果'then '不贵'
else '贵' end as 贵不贵
from test;
查询结果如图: