HIve中case应用

示例数据:

ID 姓名  年龄  消费

id name age xf

101,zs,18,10045

102,ls,56,2222
103,ww,30,16666
104,zl,42,20000
105,tom,68,3000
106,jack,70,2000
107,amy,69,60000
108,lucy,12,200
109,frank,52,40000
111,mac,25,80000
112,ace,32,60000
113,tt,12,3000
114,hh,18,10000
115,haha,25,12000
116,hehe,19,1122
117,mm,20,56121
118,gg,36,222222
119,fuck,46,33333
121,hello,56,6558
122,goon,66,7000
123,soon,76,6666
124,good,86,5000
125,aa,96,100
126,kk,10,100


创建表格:

create table hehe(id int,name string ,age string,xf int) row format delimited fields terminated by ',' stored as textfile;

加载示例数据:

load data local inpath '/home/hadoop/hehe.txt' into table hehe;

1、统计各个年龄段人数
select aa.gg,count(*) from (select case when age<20 then '0-20岁' when 20<=age and age<40 then '20-40岁' when 40<=age and age<60 then '40-60岁'  else '60岁以上' end gg from hehe) aa  group by aa.gg;



查询结果:
0-20岁  6
20-40岁 6
40-60岁 5
60岁以上 7


2、统计各个年龄段消费情况的高低
select case when age<20 then (case when xf<1000 then '低消费' when xf>=1000 and xf<20000 then '适中' else '高消费'end) 
when 20<=age and age<40 then (case when xf<1000 then '低消费' when xf>=1000 and xf<20000 then '适中' else '高消费'end)
 when 40<=age and age<60 then (case when xf<1000 then '低消费' when xf>=1000 and xf<20000 then '适中' else '高消费'end) 
 else (case when xf<1000 then '低消费' when xf>=1000 and xf<20000 then '适中' else '高消费'end) end  
 from hehe;
 

你可能感兴趣的:(Hive)