Hive sql常用函數公式整理


1.變量中文重命名:

hive sql 和SAS用中文進行變量重命名時要用反向引號(鍵盤1左邊那個鍵位)

2.日期格式轉化

year(H.l_date)*100 + month(H.l_date) as yue; 202001
date_format(active_date,'%Y-%m')='2020-01'
DATE_FORMAT(ACTIVE_DATE,"yMM")='202001'
其他日期格式:yyyymmdd, 年月日;
    yyyymm,年月;
    mm,月
    dd,日
    yyyy-mm-dd
    yyyy-mm
    yyyymmddhh24miss,年月日時分秒
    yyyy-mm-dd hh24:mi:ss
    hh24miss
    yyyymmddhh24missff3,年月日時分秒毫秒

3.間隔天數:
datediff(2019-09-01,2019-08-01) 返回31
4.返回日期格式:
to_date(2019-09-01 18:30:00) 返回2019-09-01
5.返回月初:
trunc(current_date,'MM') 返回本月1號
返回上月末:
last_day(add_months(current_date(),-1))
6.返回n天前:
date_sub(2019-09-01 18:30:00,31) 返回2019-08-01

date_sub('2016-08-01',1) 表示 2016-07-31

date_add('2016-08-01',-1) 輸出:2016-07-31

7.返回n個月前:
add_months(current_date(),-1) 前移一個月
8.上月放款:
active_date>=trunc(add_months(current_date(),-1),"MM") and active_date<=last_day(add_months(current_date(),-1))

9.${p}
sql查詢命令運行后提供選擇
10.字段拼接:
concat("a",m.loan_init_term) as `期數`
concat('2018','08') 返回201808
concat_ws(string SEP, string A, string B...)返回輸入字符串連接后的結果,SEP表示各個字符串間的分隔符
hive> select concat_ws(',','ab','cd','e') from test1;
返回:ab,cd,e
11.nvl(x,y) Returns y if x is null else return x
12.mod(n1,n2) 
返回n1 除以n2 的余數。返回值的正負和n1相關。
13.pmod(n1,n2) 
返回n1 除以n2 的余數絕對值
14. 切片
substr(string A, int start, int len)或者substring(string A, int start, int len) 
hive> select substr(‘string’,3,3) from test; 
rin
hive>select substring(‘string’,3,3) from test; 
ing

15.公式替換:
regexp_replace(string A, string B, string C) 
返回值: string,說明:將字符串A中的符合Java正則表達式B的部分替換為C。注意,在有些情況下要使用轉義字符
舉例:hive> select regexp_replace('string','rin','ron') from ccs_acct
返回strong

16.去重(取最新時點記錄)
row_number() over(partition by acct_nbr order by create_time desc) as rn where rn=1
17.等額本息計算(excel)
每月還款額=-PMT(月利率,月數,放款總額,0) 
18.等額本金計算
每月還款額=月均本金+(放款金額-月均本金*i)*月利率
19.通配符
where city like '[ALN]%'----篩選city 以‘A’,‘L’,‘N’開頭的記錄
where city like 'ne%'-----篩選city以'ne'開頭的記錄
where city like '%ne%'-----篩選city包含'ne'的記錄
where city like '_enan'-----篩選city第一個字符之后是'enan'的記錄
20.其他日期相關匯總: 
from_unixtime:轉化unix時間戳到當前時區的時間格式 
select from_unixtime(1587361271,'yyyyMMdd') from ccs_acct 
輸出:20200420 
unix_timestamp:獲取當前unix時間戳 
select unix_timestamp(); 
輸出:1587361271 
select unix_timestamp('2020-04-20 14:20:03') from ccs_acct
輸出:1587363603
select unix_timestamp('2020-04-19 14:20:03') from ccs_acct 
輸出:1587277203

hour:返回日期中的小時 
select hour('2020-04-20 14:20:03'); 
輸出:14

minute:返回日期中的分鍾 
select minute('2020-04-20 14:20:03'); 
輸出:20 

second:返回日期中的秒 
select second('2020-04-20 14:20:03'); 
輸出:3

weekofyear:返回日期在當前周數 
select weekofyear('2020-04-20 14:20:03'); 
輸出:17

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM