天天看點

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

對于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,