case when then else end的用法

主要分为两种:简单case函数和搜索case函数

简单case函数

case column 
when 'A' then 'a' 
when 'B' then 'b' 
else 0 end;

搜索case函数

case when column='A' then 'a'
when column='B' then 'b'
else 0 end;

简单case函数语法比较简洁,但是较搜索case函数而言,功能上会有所限制.下面重点总结下搜索case函数的常见用法.

所有case…when…用法的本质都是:给已知数据重新赋值形成新的字段
需要注意的:不加else条件,会默认返回null
(hive中必须要加else语句)

常见用法1 : 重新分组
table A的数据如下:

countryflower_classes
中国2000
印度1000
法国3000
英国2000
意大利2500
新西兰3000
美国1500

按照洲的名称统计花的种类,计算sql如下:

select sum(flower_classes)  as flower_classes
,case when country = '中国'  then '亚洲'
 when country = '印度'  then '亚洲'
 when country = '法国'  then '欧洲'
 when country = '英国'  then '欧洲'
 when country = '意大利'  then '欧洲'
 when country = '新西兰'  then '大洋洲' 
 end as continent
from table A
group by 
 case when country = '中国'  then '亚洲'
 when country = '印度'  then '亚洲'
 when country = '法国'  then '欧洲'
 when country = '英国'  then '欧洲'
 when country = '意大利'  then '欧洲'
 when country = '新西兰'  then '大洋洲' 
 end;

常见方法2 : 与聚合函数一起使用
table B的数据如下:

citysexpopulation
武汉1000
武汉2000
长沙500
长沙600
上海1000
上海2000
北京1500
北京2000
深圳3000
深圳4000
分别统计男女的人口数量,计算sql如下:
select 
from 
sum(case when sex='男' then population else 0 end) as male_population
,sum(case when sex='女' then population else 0 end) as 
female_population 
from table B

常见用法3:与聚合函数一起使用
table C的数据如下:

nameclub_idclub_namemain_club_id
林一1羽毛球1
小白2篮球0
小白3足球1
大黄2篮球1
大黄3足球0
大黄4游泳0
小麦4游泳1
数据解释:如果此人只加入了1个社团,其main_club_id设为1;如果此人加入的社团大于1个,主社团的main_club_id设为1,其他为0.
要求统计:对于只加入1个社团的人,其club_id;加入多个社团的人,其主社团的club_id.统计sql如下:
select 
case when count(club_id)=1 then max(club_id)
else max(case when main_club_id=1 then club_id end) 
end as main_club_id 
from table C
group by name

参考链接

  • 5
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值