主要分为两种:简单case函数和搜索case函数
1️⃣简单case函数
case column
when 'A' then 'a'
when 'B' then 'b'
else 0 end;
2️⃣搜索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的数据如下:
按照洲的名称统计花的种类,计算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的数据如下:
分别统计男女的人口数量,计算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的数据如下:
数据解释:如果此人只加入了1个社团,其main_club_id设为1;如果此人加入的社团大于1个,主社团的main_club_id设为1,其他为0.
要求统计:对于只加入1个社团的人,其club_ids;加入多个社团的人,其主社团的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