hive常用内部函数

hive常用内部函数

hive是一种典型的数据仓库分析工具,常用语编写hql语句进行指标分析。在编写hql的过程中无疑会用到很多的函数,哪本章来编写一些常见的函数。常见函数很多,不同常见不同人员,使用不一样,不喜勿喷。

1、随机函数rand()

格式:rand([int seed])
返回:double

-- 取0-1的随机值
select rand();
-- 指定随机函数的种子seed,该随机会返回一个固定值
select rand(100);

2、切分函数split()

格式:split(str,spliter)
返回:array

-- 获取随机数*100,然后再取整。小数点.需要转义
select split(rand()*100,'\\.')[0];

3、字符串截取函数substring() 或 substr()

格式:substring(str,start,length)      substr(str,start,length)
返回:string

-- 获取随机数*100,然后再从0位置开始,取2位字符串。
select substring(rand()*100,0,2);

-- 获取随机数*100,然后再从0位置开始,取2位字符串。
select substr(rand()*100,0,2);

4、判断函数if()

格式:if(condition,true,false)
返回:true或者flase部分的值

-- 查询s_tmp表,如果s.sex等于1,则是男,否则是女
select
s.id,
s.name,
if(s.sex = 1,'男','女')
from s_tmp s
;

-- if嵌套查询
select
s.id,
s.name,
if(s.id = 1,'男',if(s.id = 2,'女','妖'))
from s_tmp s
;

5、选择函数case when

类似于java中的swith。比if函数更加的具有扩展性。
格式:
casewhen 1 then ''
...
else
end

返回:then或者else后的值

格式2case
when=1 then ''
...
else
end

返回:then或者else后的值


-- 查询s_tmp中的s.sex,如果为1,则是男,为2则是女,其它为妖
select
s.id,
s.name,
case s.sex
when 1 then '男'
when 2 then '女'
else '妖'
end
from s_tmp s
;

-- 查询s_tmp中的s.sex,如果为1,则是男,为2则是女,其它为妖
select
s.id,
s.name,
case
when s.sex=1 then '男'
when s.sex=2 then '女'
else '妖'
end
from s_tmp s
;

6、正在替换函数regexp_replace()

格式:regexp_replace(str,old_string,new_str)   #old_string支持通配符
返回:string

-- 将.png替换为.jpg
select regexp_replace('1.png','.png','.jpg');

-- 将s.name的名字为zhangsan的替换为lisi
select
s.id,
regexp_replace(s.name,'zhangsan','lisi')
from s_tmp s
;

7、类型转换 函数cast()

格式: cast(x as type)
返回:type类型

-- 将1.0转换成int类型
select cast(1.0 as int);

-- 将随机数*100,转换成int类型
select cast(rand()*100 as int);

8、四舍五入函数round()

格式:round(double,保留位数)
返回:double

-- 随机数*100,然后四舍五入取值。没有保留位数默认四舍五入取整,比如0.0 或者 1.0
select round(rand()*100);

-- 随机数*100,然后保留两位小数,四舍五入取值
select round(rand()*100,2);

9、连接函数concat() 或者 concat_ws()

格式:concat(str1,str2...) 或者 concat_ws(split_str,str1,str2....)
返回:string

-- 将字符串1,2拼接起来
select concat("1","2");

-- 将字符串1,2拼接起来,并使用|来进行分割
select concat_ws("|","1","3","2");

-- 将id,name,sex使用|进行拼接
select
concat_ws('|',cast(s.id as string),s.name,cast(s.sex as string))
from s_tmp s
;

10、字符串长度函数length()

格式:length(str) 
返回:int

-- 获取name的长度
select
length(s.name)
from s_tmp s
;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章