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
;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章