Hive sql經常使用函數

1.獲取當前日期 如2020-13-22

current_date() 或者 current_date
獲取當前時間from_unixtime(unix_timestamp()) -->返回格式:yyyy-MM-dd HH:mm:ss
      : current_timestamp()                  -->返回格式:yyyy-MM-dd HH:mm:ss.xxx

2.時間戳轉爲日期

from_unixtime(時間戳,string format=yyyy-MM-dd HH:mm:ss)   //實際寫出來不須要帶string,只是代表格式
--時間戳爲10位,H爲24小時計數,h爲12小時計數
--string format:默認標準格式爲 yyyy-MM-dd HH:mm:ss
--其餘格式寫法多種多樣 yyyy-MM-dd HH:mm
--yyyy-MM-dd HH
--yyyy-MM-dd
--yyyyMMdd
--yyyy/MM/dd

3.日期轉爲時間戳

unix_timestamp(string date=當前時間)   //實際寫出來不須要帶string,只是代表格式
--默認爲獲取當前時間戳: unix_timestamp()
--date的格式必須是 標準格式:" yyyy-MM-dd HH:mm:ss",如不符合返回null

4.時間間隔計算  --(理解:date difference日期差別)

datediff(string enddate,string startdate)
--計算方式爲:enddate-startdate
--結果爲天數

5.保留年月日

to_date("標準時間格式")
--結果爲如:2020-03-22

6.單獨年,月,日

year(format_date)
month(format_date)
day(format_date)
-- format_date格式至少包含年月日
-- 如year("2020-03-22")
-- year("2020-03-22 12:23")

7.日期增長函數

date_add(string startdate,intdays)
--如:date_add("2020-03-11",10) -->2020-03-21

8.日期減小函數

date_sub(string startdate,intdays)
--如:date_add("2020-03-11",10) -->2020-03-01

9.截取字符串

substr(str,pos,len)
-- 經常使用於截取字符串時間
-- pos從1開始算,不是0

10.條件函數:case when

--如:select case when age<20 then "20歲如下"
when age>=20 and age<30 then "20~30歲"
when age>=30 and age<40 then "30~40歲"
else "40歲以上" end as age_type,
count (distinct user_id) user_num
from user_info
group by ...;

11.if函數

if(條件表達式,結果1,結果2) :當條件爲真-->結果1,不然結果2
--如:select if (level>5,"高","低") [as level_type] from...

12.對json字符串和map類型的處理

get_json_object(string json_string,string path)
string json_string:列名
string path:用$.key取值
--如:字段: extra1(string): {"systemtype":"ios","education":"master","marriage_status":"1","phone brand":"iphone X"}
--字段: extra2(map<string,string>): {"systemtype":"ios","education":"master","marriage_status":"1","phone brand":"iphone X"}
對於json類型:
例如:
SELECT get_json_object(extra1, '$.phonebrand') as phone_brand,
count(distinct user_id) user_num
FROM user_info
GROUP BY get_json_object(extra1, '$.phonebrand');

對於map類型:
例如:select extra2['phonebrand'] as phone_brand,
count(distinct user_id) user_num
FROM user_info
GROUP BY extra2['phonebrand'];
相關文章
相關標籤/搜索