函数
Hive中的函数
针对内置的函数,可以根据函数的应用类型进行归纳分类,比如:数值类型函数、日期类型函数、字符
串类型函数、集合函数、条件函数等;
针对用户自定义函数,可以根据函数的输入输出行数进行分类,比如:UDF、UDAF、UDTF。
在Hive中,所有的函数都不能直接使用,必须结合select形成语句才能使用
描述函数的信息:desc function count;desc function sqrt;
查看Hive中的所有函数 show functions;
字符串拼接
1.拼接多个字符串,并且在拼接的时候指定字符串之间的间隔符号 webs.txt
mail qq com
smtp qq com
mail 163 com
hive
create table webs(a1 string, a2 string, a3 string) row format delimited fields terminated by ' ';
load data local inpath '/data/webs.txt' into table webs;'
select concat(a1, '.', a2, '.', a3) from webs;
select concat_ws('.', app, company, kind) from webs;
select concat_ws('.', *) from webs;
split
select cast(split('2024-8-12','-')[0]as int);
select year('2024-8-12');
select cast(split('2024/8/12', '/')[0] as int);
select split('tom@tedu.cn', '@')[1];
select year(regexp_replace('2024/8/19', '/', '-'));
nvl
nvl(s1, s2):如果s1的值不为null,那么返回s1的值;如果s1的值为null那么返回s2的值;如果s1和s2的值都为null,那么返回null
原始数据order.txt
1 wang 120
2 zhangsan 80
3 lisi
4 himeimei 120
create table order(id int, name string, money double) row format delimited fields terminated by ' ';
加载数据:
load data local inpath '/order.txt' into table order;
计算平均每个人物赚了多少钱,如果碰到null自动忽略:
select avg(nvl(money,0)) from order;
select sum(money) from order;
select avg(money) from order;
case when 函数
Java中的switch-case结构
数据:employer.txt
1 jishu wjm man
2 renshi lilei woman
create table employer(id int,department string,name string, sexstring) row format delimited fields terminated by ' ';
加载数据:
load data local inpath '/employer.txt' into table employer;
统计每一个部门的总人数:
select department, count(*) from employer group by department;
统计每一个部门男女生的总人数:
select department, sum(case sex when 'man' then 1 else 0 end) as sum_man, sum(case sex when 'woman' then 1 else 0 end) as sum_woman from employer group by department;
explode
select split('a-b-c','-') ;得到结果["a","b","c"]
select explode(('a-b-c','-')) ;
拆分键值对
我们将map结果的键值对通过explode拆分成单独的值
可以使用这个函数进行单词统计的列子
数据words.txt,在/目录下建立words文件夹,把words.txt放进去
hello tom hello bob jack world hello
hello weilan joy hello wjm
world hello tom hello joy
create external table words(wordarray array<string>) row format delimited collection items terminated by ' ' location '/words';
select * from words;
其中select explode(wordarray) w from words是一个子查询,结果放到ws这个临时表中,其中又给字段给了一个别名w,外面就对w进行操作。
select w, count(w) from (select explode(wordarray ) w from words)ws group by w;