柚子快報邀請碼778899分享:hive sql 語句查詢規(guī)則
柚子快報邀請碼778899分享:hive sql 語句查詢規(guī)則
一、單表查詢
SELECT [ALL | DISTINCT] select_expr, select_expr, ...
FROM table_reference
[WHERE where_condition]
[GROUP BY col_list [HAVING condition]]
[CLUSTER BY col_list
| [DISTRIBUTE BY col_list] [SORT BY| ORDER BY col_list]
]
[LIMIT number]
注意: 1、order by 會對輸入做全局排序,因此只有一個reducer,會導致當輸入規(guī)模較大時,需要較長的計算時間。 2、sort by不是全局排序,其在數(shù)據(jù)進入reducer前完成排序。因此,如果用sort by進行排序,并且設(shè)置mapred.reduce.tasks>1,則sort by只保證每個reducer的輸出有序,不保證全局有序。 3、distribute by(字段)根據(jù)指定的字段將數(shù)據(jù)分到不同的reducer,且分發(fā)算法是hash散列。 4、Cluster by(字段) 除了具有Distribute by的功能外,還會對該字段進行排序。 因此,如果分桶和sort字段是同一個時,此時,cluster by = distribute by + sort by
1.1 WHERE語句
select * from score where s_score < 60;
注意: 小于某個值是不包含null的,如上查詢結(jié)果是把 s_score 為 null 的行剔除的
1.2 GROUP BY 分組
select s_id ,avg(s_score) from score group by s_id;
分組后對數(shù)據(jù)進行篩選,使用having
select s_id ,avg(s_score) avgscore from score group by s_id having avgscore > 85;
注意:
如果使用 group by 分組,則 select 后面只能寫分組的字段或者聚合函數(shù)
where和having區(qū)別:
1 having是在 group by 分完組之后再對數(shù)據(jù)進行篩選,所以having 要篩選的字段只能是分組字段或者聚合函數(shù)
2 where 是從數(shù)據(jù)表中的字段直接進行的篩選的,所以不能跟在gruop by后面,也不能使用聚合函數(shù)
1.3 join 連接
INNER JOIN 內(nèi)連接:只有進行連接的兩個表中都存在與連接條件相匹配的數(shù)據(jù)才會被保留下來
select * from techer t [inner] join course c on t.t_id = c.t_id; -- inner 可省略
LEFT OUTER JOIN 左外連接:左邊所有數(shù)據(jù)會被返回,右邊符合條件的被返回
select * from techer t left join course c on t.t_id = c.t_id; -- outer可省略
RIGHT OUTER JOIN 右外連接:右邊所有數(shù)據(jù)會被返回,左邊符合條件的被返回、
select * from techer t right join course c on t.t_id = c.t_id;
FULL OUTER JOIN 滿外(全外)連接: 將會返回所有表中符合條件的所有記錄。如果任一表的指定字段沒有符合條件的值的話,那么就使用NULL值替代。
SELECT * FROM techer t FULL JOIN course c ON t.t_id = c.t_id ;
注:1. hive2版本已經(jīng)支持不等值連接,就是 join on條件后面可以使用大于小于符號了;并且也支持 join on 條件后跟or (早前版本 on 后只支持 = 和 and,不支持 > < 和 or)
2.如hive執(zhí)行引擎使用MapReduce,一個join就會啟動一個job,一條sql語句中如有多個join,則會啟動多個job
注意:表之間用逗號(,)連接和 inner join 是一樣的
select * from table_a,table_b where table_a.id=table_b.id;
它們的執(zhí)行效率沒有區(qū)別,只是書寫方式不同,用逗號是sql 89標準,join 是sql 92標準。用逗號連接后面過濾條件用 where ,用 join 連接后面過濾條件是 on。
1.4 order by 排序
全局排序,只會有一個reduce
ASC(ascend): 升序(默認) DESC(descend): 降序
SELECT * FROM student s LEFT JOIN score sco ON s.s_id = sco.s_id ORDER BY sco.s_score DESC;
注意:order by 是全局排序,所以最后只有一個reduce,也就是在一個節(jié)點執(zhí)行,如果數(shù)據(jù)量太大,就會耗費較長時間
1.5 sort by 局部排序
查詢成績按照成績降序排列
select * from score sort by s_score;
1.6 distribute by 分區(qū)排序
distribute by:類似MR中partition,進行分區(qū),結(jié)合sort by使用
通過distribute by 進行數(shù)據(jù)的分區(qū)
select * from score distribute by s_id sort by s_score;
注意:Hive要求 distribute by 語句要寫在 sort by 語句之前
1.7 cluster by
當distribute by和sort by字段相同時,可以使用cluster by方式.
cluster by除了具有distribute by的功能外還兼具sort by的功能。但是排序只能是正序排序,不能指定排序規(guī)則為ASC或者DESC。
以下兩種寫法等價
select * from score cluster by s_id;
select * from score distribute by s_id sort by s_id;
二、Hive函數(shù)
2.1 聚合函數(shù)-count(),max(),min(),sum(),avg()
注意:
聚合操作時要注意null值
count(*) 包含null值,統(tǒng)計所有行數(shù)
count(id) 不包含null值
min 求最小值是不包含null,除非所有值都是null
avg 求平均值也是不包含null
非空集合總體變量函數(shù): var_pop
語法: var_pop(col)
返回值: double
說明: 統(tǒng)計結(jié)果集中col非空集合的總體變量(忽略null)
非空集合樣本變量函數(shù): var_samp
語法: var_samp (col)
返回值: double
說明: 統(tǒng)計結(jié)果集中col非空集合的樣本變量(忽略null)
總體標準偏離函數(shù): stddev_pop
語法: stddev_pop(col)
返回值: double
說明: 該函數(shù)計算總體標準偏離,并返回總體變量的平方根,其返回值與VAR_POP函數(shù)的平方根相同
中位數(shù)函數(shù): percentile
語法: percentile(BIGINT col, p)
返回值: double
說明: 求準確的第pth個百分位數(shù),p必須介于0和1之間,但是col字段目前只支持整數(shù),不支持浮點數(shù)類型
2.2 關(guān)系運算
支持:等值(=)、不等值(!= 或 <>)、小于(<)、小于等于(<=)、大于(>)、大于等于(>=)
空值判斷(is null)、非空判斷(is not null)
LIKE比較: LIKE
語法: A LIKE B
操作類型: strings
描述: 如果字符串A或者字符串B為NULL,則返回NULL;如果字符串A符合表達式B 的正則語法,則為TRUE;否則為FALSE。B中字符”_”表示任意單個字符,而字符”%”表示任意數(shù)量的字符。
JAVA的LIKE操作: RLIKE
語法: A RLIKE B
操作類型: strings
描述: 如果字符串A或者字符串B為NULL,則返回NULL;如果字符串A符合JAVA正則表達式B的正則語法,則為TRUE;否則為FALSE。
REGEXP操作: REGEXP
語法: A REGEXP B
操作類型: strings
描述: 功能與RLIKE相同
示例:select 1 from tableName where 'footbar' REGEXP '^f.*r$';
結(jié)果:1
2.3 數(shù)學運算
支持所有數(shù)值類型:加(+)、減(-)、乘(*)、除(/)、取余(%)、位與(&)、位或(|)、位異或(^)、位取反(~)
2.4 邏輯運算
支持:邏輯與(and)、邏輯或(or)、邏輯非(not)
2.5 數(shù)值運算
取整函數(shù): round
語法: round(double a)
返回值: BIGINT
說明: 返回double類型的整數(shù)值部分 (遵循四舍五入)
示例:select round(3.1415926) from tableName;
結(jié)果:3
指定精度取整函數(shù): round
語法: round(double a, int d)
返回值: DOUBLE
說明: 返回指定精度d的double類型
hive> select round(3.1415926,4) from tableName;
3.1416
向下取整函數(shù): floor
語法: floor(double a)
返回值: BIGINT
說明: 返回等于或者小于該double變量的最大的整數(shù)
hive> select floor(3.641) from tableName;
3
向上取整函數(shù): ceil
語法: ceil(double a)
返回值: BIGINT
說明: 返回等于或者大于該double變量的最小的整數(shù)
hive> select ceil(3.1415926) from tableName;
4
取隨機數(shù)函數(shù): rand
語法: rand(),rand(int seed)
返回值: double
說明: 返回一個0到1范圍內(nèi)的隨機數(shù)。如果指定種子seed,則會等到一個穩(wěn)定的隨機數(shù)序列
hive> select rand() from tableName; -- 每次執(zhí)行此語句得到的結(jié)果都不同
0.5577432776034763
hive> select rand(100) ; -- 只要指定種子,每次執(zhí)行此語句得到的結(jié)果一樣的
0.7220096548596434
自然指數(shù)函數(shù): exp
語法: exp(double a)
返回值: double
說明: 返回自然對數(shù)e的a次方
hive> select exp(2) ;
7.38905609893065
以10為底對數(shù)函數(shù): log10
語法: log10(double a)
返回值: double
說明: 返回以10為底的a的對數(shù)
hive> select log10(100) ;
2.0
此外還有:以2為底對數(shù)函數(shù): log2()、對數(shù)函數(shù): log()
冪運算函數(shù): pow
語法: pow(double a, double p)
返回值: double
說明: 返回a的p次冪
hive> select pow(2,4) ;
16.0
開平方函數(shù): sqrt
語法: sqrt(double a)
返回值: double
說明: 返回a的平方根
hive> select sqrt(16) ;
4.0
二進制函數(shù): bin
語法: bin(BIGINT a)
返回值: string
說明: 返回a的二進制代碼表示
hive> select bin(7) ;
111
十六進制函數(shù): hex()、將十六進制轉(zhuǎn)化為字符串函數(shù): unhex()
進制轉(zhuǎn)換函數(shù): conv(bigint num, int from_base, int to_base) 說明: 將數(shù)值num從from_base進制轉(zhuǎn)化到to_base進制
此外還有很多數(shù)學函數(shù):絕對值函數(shù): abs()、正取余函數(shù): pmod()、正弦函數(shù): sin()、反正弦函數(shù): asin()、余弦函數(shù): cos()、反余弦函數(shù): acos()、positive函數(shù): positive()、negative函數(shù): negative()
2.6 條件函數(shù)
If函數(shù): if
語法: if(boolean testCondition, T valueTrue, T valueFalseOrNull)
返回值: T
說明: 當條件testCondition為TRUE時,返回valueTrue;否則返回valueFalseOrNull
hive> select if(1=2,100,200) ;
200
hive> select if(1=1,100,200) ;
100
非空查找函數(shù): coalesce
語法: coalesce(T v1, T v2, …)
返回值: T
說明: 返回參數(shù)中的第一個非空值;如果所有值都為NULL,那么返回NULL
hive> select coalesce(null,'100','50') ;
100
條件判斷函數(shù):case when (兩種寫法,其一)
語法: case when a then b [when c then d]* [else e] end
返回值: T
說明:如果a為TRUE,則返回b;如果c為TRUE,則返回d;否則返回e
hive> select case when 1=2 then 'tom' when 2=2 then 'mary' else 'tim' end from tableName;
mary
條件判斷函數(shù):case when (兩種寫法,其二)
語法: case a when b then c [when d then e]* [else f] end
返回值: T
說明:如果a等于b,那么返回c;如果a等于d,那么返回e;否則返回f
hive> Select case 100 when 50 then 'tom' when 100 then 'mary' else 'tim' end from tableName;
mary
2.7 日期函數(shù)
注:以下SQL語句中的 from tableName 可去掉,不影響查詢結(jié)果
獲取當前UNIX時間戳函數(shù): unix_timestamp
語法: unix_timestamp()
返回值: bigint
說明: 獲得當前時區(qū)的UNIX時間戳
hive> select unix_timestamp() from tableName;
1616906976
UNIX時間戳轉(zhuǎn)日期函數(shù): from_unixtime
語法: from_unixtime(bigint unixtime[, string format])
返回值: string
說明: 轉(zhuǎn)化UNIX時間戳(從1970-01-01 00:00:00 UTC到指定時間的秒數(shù))到當前時區(qū)的時間格式
hive> select from_unixtime(1616906976,'yyyyMMdd') from tableName;
20210328
日期轉(zhuǎn)UNIX時間戳函數(shù): unix_timestamp
語法: unix_timestamp(string date)
返回值: bigint
說明: 轉(zhuǎn)換格式為"yyyy-MM-dd HH:mm:ss"的日期到UNIX時間戳。如果轉(zhuǎn)化失敗,則返回0。
hive> select unix_timestamp('2021-03-08 14:21:15') from tableName;
1615184475
指定格式日期轉(zhuǎn)UNIX時間戳函數(shù): unix_timestamp
語法: unix_timestamp(string date, string pattern)
返回值: bigint
說明: 轉(zhuǎn)換pattern格式的日期到UNIX時間戳。如果轉(zhuǎn)化失敗,則返回0。
hive> select unix_timestamp('2021-03-08 14:21:15','yyyyMMdd HH:mm:ss') from tableName;
1615184475
日期時間轉(zhuǎn)日期函數(shù): to_date
語法: to_date(string timestamp)
返回值: string
說明: 返回日期時間字段中的日期部分。
hive> select to_date('2021-03-28 14:03:01') from tableName;
2021-03-28
日期轉(zhuǎn)年函數(shù): year
語法: year(string date)
返回值: int
說明: 返回日期中的年。
hive> select year('2021-03-28 10:03:01') from tableName;
2021
hive> select year('2021-03-28') from tableName;
2021
日期轉(zhuǎn)月函數(shù): month
語法: month (string date)
返回值: int
說明: 返回日期中的月份。
hive> select month('2020-12-28 12:03:01') from tableName;
12
hive> select month('2021-03-08') from tableName;
8
日期轉(zhuǎn)天函數(shù): day
語法: day (string date)
返回值: int
說明: 返回日期中的天。
hive> select day('2020-12-08 10:03:01') from tableName;
8
hive> select day('2020-12-24') from tableName;
24
日期轉(zhuǎn)小時函數(shù): hour
語法: hour (string date)
返回值: int
說明: 返回日期中的小時。
hive> select hour('2020-12-08 10:03:01') from tableName;
10
日期轉(zhuǎn)分鐘函數(shù): minute
語法: minute (string date)
返回值: int
說明: 返回日期中的分鐘。
hive> select minute('2020-12-08 10:03:01') from tableName;
3
日期轉(zhuǎn)秒函數(shù): second
語法: second (string date)
返回值: int
說明: 返回日期中的秒。
hive> select second('2020-12-08 10:03:01') from tableName;
1
日期轉(zhuǎn)周函數(shù): weekofyear
語法: weekofyear (string date)
返回值: int
說明: 返回日期在當前的周數(shù)。
hive> select weekofyear('2020-12-08 10:03:01') from tableName;
49
日期比較函數(shù): datediff
語法: datediff(string enddate, string startdate)
返回值: int
說明: 返回結(jié)束日期減去開始日期的天數(shù)。
hive> select datediff('2020-12-08','2012-05-09') from tableName;
213
日期增加函數(shù): date_add
語法: date_add(string startdate, int days)
返回值: string
說明: 返回開始日期startdate增加days天后的日期。
hive> select date_add('2020-12-08',10) from tableName;
2020-12-18
日期減少函數(shù): date_sub
語法: date_sub (string startdate, int days)
返回值: string
說明: 返回開始日期startdate減少days天后的日期。
hive> select date_sub('2020-12-08',10) from tableName;
2020-11-28
日期常用函數(shù)
//昨天
select format_datetime(date_add('day',-1,current_date),'yyyyMMdd')
// 月份
select substr(cast(current_date as varchar) , 1 ,7 )
//獲取上月月初
select date_trunc('month', (date_add('day', - day_of_month(current_date), current_date)));
上個月月末
select date_add('day', - day_of_month(current_date), current_date);
//月初
select date_trunc('month',current_date)
//月末
SELECT date_add('day', -1, date_add('month', 1, date_trunc('month', current_date)))
2.8 字符串函數(shù)
字符串長度函數(shù):length
語法: length(string A)
返回值: int
說明:返回字符串A的長度
hive> select length('abcedfg') from tableName;
7
字符串反轉(zhuǎn)函數(shù):reverse
語法: reverse(string A)
返回值: string
說明:返回字符串A的反轉(zhuǎn)結(jié)果
hive> select reverse('abcedfg') from tableName;
gfdecba
字符串連接函數(shù):concat
語法: concat(string A, string B…)
返回值: string
說明:返回輸入字符串連接后的結(jié)果,支持任意個輸入字符串
hive> select concat('abc','def’,'gh')from tableName;
abcdefgh
帶分隔符字符串連接函數(shù):concat_ws
語法: concat_ws(string SEP, string A, string B…)
返回值: string
說明:返回輸入字符串連接后的結(jié)果,SEP表示各個字符串間的分隔符
hive> select concat_ws(',','abc','def','gh')from tableName;
abc,def,gh
字符串截取函數(shù):substr,substring
語法: substr(string A, int start),substring(string A, int start)
返回值: string
說明:返回字符串A從start位置到結(jié)尾的字符串
hive> select substr('abcde',3) from tableName;
cde
hive> select substring('abcde',3) from tableName;
cde
hive> select substr('abcde',-1) from tableName; (和ORACLE相同)
e
字符串截取函數(shù):substr,substring
語法: substr(string A, int start, int len),substring(string A, int start, int len)
返回值: string
說明:返回字符串A從start位置開始,長度為len的字符串
hive> select substr('abcde',3,2) from tableName;
cd
hive> select substring('abcde',3,2) from tableName;
cd
hive>select substring('abcde',-2,2) from tableName;
de
字符串轉(zhuǎn)大寫函數(shù):upper,ucase
語法: upper(string A) ucase(string A)
返回值: string
說明:返回字符串A的大寫格式
hive> select upper('abSEd') from tableName;
ABSED
hive> select ucase('abSEd') from tableName;
ABSED
字符串轉(zhuǎn)小寫函數(shù):lower,lcase
語法: lower(string A) lcase(string A)
返回值: string
說明:返回字符串A的小寫格式
hive> select lower('abSEd') from tableName;
absed
hive> select lcase('abSEd') from tableName;
absed
去空格函數(shù):trim
語法: trim(string A)
返回值: string
說明:去除字符串兩邊的空格
hive> select trim(' abc ') from tableName;
abc
左邊去空格函數(shù):ltrim
語法: ltrim(string A)
返回值: string
說明:去除字符串左邊的空格
hive> select ltrim(' abc ') from tableName;
abc
右邊去空格函數(shù):rtrim
語法: rtrim(string A)
返回值: string
說明:去除字符串右邊的空格
hive> select rtrim(' abc ') from tableName;
abc
正則表達式替換函數(shù):regexp_replace
語法: regexp_replace(string A, string B, string C)
返回值: string
說明:將字符串A中的符合java正則表達式B的部分替換為C。注意,在有些情況下要使用轉(zhuǎn)義字符,類似oracle中的regexp_replace函數(shù)。
hive> select regexp_replace('foobar', 'oo|ar', '') from tableName;
fb
正則表達式解析函數(shù):regexp_extract
語法: regexp_extract(string subject, string pattern, int index)
返回值: string
說明:將字符串subject按照pattern正則表達式的規(guī)則拆分,返回index指定的字符。
hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 1) from tableName;
the
hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 2) from tableName;
bar
hive> select regexp_extract('foothebar', 'foo(.*?)(bar)', 0) from tableName;
foothebar
strong>注意,在有些情況下要使用轉(zhuǎn)義字符,下面的等號要用雙豎線轉(zhuǎn)義,這是java正則表達式的規(guī)則。
select data_field,
regexp_extract(data_field,'.*?bgStart\\=([^&]+)',1) as aaa,
regexp_extract(data_field,'.*?contentLoaded_headStart\\=([^&]+)',1) as bbb,
regexp_extract(data_field,'.*?AppLoad2Req\\=([^&]+)',1) as ccc
from pt_nginx_loginlog_st
where pt = '2021-03-28' limit 2;
URL解析函數(shù):parse_url
語法: parse_url(string urlString, string partToExtract [, string keyToExtract])
返回值: string
說明:返回URL中指定的部分。partToExtract的有效值為:HOST, PATH, QUERY, REF, PROTOCOL, AUTHORITY, FILE, and USERINFO.
hive> select parse_url
('https://www.tableName.com/path1/p.php?k1=v1&k2=v2#Ref1', 'HOST')
from tableName;
www.tableName.com
hive> select parse_url
('https://www.tableName.com/path1/p.php?k1=v1&k2=v2#Ref1', 'QUERY', 'k1')
from tableName;
v1
json解析函數(shù):get_json_object
語法: get_json_object(string json_string, string path)
返回值: string
說明:解析json的字符串json_string,返回path指定的內(nèi)容。如果輸入的json字符串無效,那么返回NULL。
hive> select get_json_object('{"store":{"fruit":\[{"weight":8,"type":"apple"},{"weight":9,"type":"pear"}], "bicycle":{"price":19.95,"color":"red"} },"email":"amy@only_for_json_udf_test.net","owner":"amy"}','$.owner') from tableName;
空格字符串函數(shù):space
語法: space(int n)
返回值: string
說明:返回長度為n的字符串
hive> select space(10) from tableName;
hive> select length(space(10)) from tableName;
10
重復(fù)字符串函數(shù):repeat
語法: repeat(string str, int n)
返回值: string
說明:返回重復(fù)n次后的str字符串
hive> select repeat('abc',5) from tableName;
abcabcabcabcabc
首字符ascii函數(shù):ascii
語法: ascii(string str)
返回值: int
說明:返回字符串str第一個字符的ascii碼
hive> select ascii('abcde') from tableName;
97
左補足函數(shù):lpad
語法: lpad(string str, int len, string pad)
返回值: string
說明:將str進行用pad進行左補足到len位
hive> select lpad('abc',10,'td') from tableName;
tdtdtdtabc
注意:與GP,ORACLE不同,pad 不能默認
右補足函數(shù):rpad
語法: rpad(string str, int len, string pad)
返回值: string
說明:將str進行用pad進行右補足到len位
hive> select rpad('abc',10,'td') from tableName;
abctdtdtdt
分割字符串函數(shù): split
語法: split(string str, string pat)
返回值: array
說明: 按照pat字符串分割str,會返回分割后的字符串數(shù)組
hive> select split('abtcdtef','t') from tableName;
["ab","cd","ef"]
集合查找函數(shù): find_in_set
語法: find_in_set(string str, string strList)
返回值: int
說明: 返回str在strlist第一次出現(xiàn)的位置,strlist是用逗號分割的字符串。如果沒有找該str字符,則返回0
hive> select find_in_set('ab','ef,ab,de') from tableName;
2
hive> select find_in_set('at','ef,ab,de') from tableName;
0
三、json字符串操作
3.1. 解析json對象-get_json_object
select
get_json_object('{"name":"zhangsan","age":18}','$.name'),
get_json_object('{"name":"zhangsan","age":18}','$.age');
3.2.解析json對象-?json_tuple
說明:解析json的字符串json_string,可指定多個json數(shù)據(jù)中的key,返回對應(yīng)的value。如果輸入的json字符串無效,那么返回NULL;json_tuple相當于get_json_object的優(yōu)勢就是一次可以解析多個json字段。但是如果我們有個json數(shù)組,這兩個函數(shù)都無法處理
示例:
select b.name ,b.age
from tableName a lateral view
json_tuple('{"name":"zhangsan","age":18}','name','age') b as name,age;
結(jié)果:
3.3 json數(shù)組-explode函數(shù)
如果有一個hive表,表中? json_str? 字段的內(nèi)容如下:[ {"website":"baidu.com","name":百度"},{"website":"google.com","name":谷歌"} ]我們想把這個字段解析出來,形成如下的結(jié)構(gòu):websitenamebaidu.com百度google.com谷歌
說明:explode()函數(shù)接收一個array或者map類型的數(shù)據(jù)作為輸入,然后將array或map里面的元素按照每行的形式輸出,即將hive一列中復(fù)雜的array或者map結(jié)構(gòu)拆分成多行顯示,也被稱為列轉(zhuǎn)行函數(shù)
示例
-- 解析array
hive> select explode(array('A','B','C'));
ok
A
B
C
-- 解析map
hive> select explode(map('A',10,'B',20,'C','30'));
OK
A 10
B 20
C 30
3.4 json數(shù)組regexp_replace函數(shù)
語法: regexp_replace(string A, string B, string C)
說明: 將字符串A中的符合 java 正則表達式的B的部分替換為C。注意:在有些情況下要使用轉(zhuǎn)義字符,類似 oracle 中的 regexp_replace 函數(shù)。
示例:
hive> select regexp_replace('roobar', 'oo|ar', '');
ok
fb
上述示例將字符串中的 oo 或 ar 替換為 ''.
先將數(shù)據(jù)轉(zhuǎn)換成對象行
hive> SELECT explode(split(regexp_replace(regexp_replace('[{"website":"baidu.com","name":"百度"},{"website":"google.com","name":"谷歌"}]', '\\[|\\]',''),'\\}\\,\\{','\\}\\;\\{'),'\\;'));
OK
{"website":"baidu.com","name":"百度"}
{"website":"google.com","name":"谷歌"}
對上述sql進行簡要說明:
SELECT explode(split(
regexp_replace(
regexp_replace(
'[
{"website":"baidu.com","name":"百度"},
{"website":"google.com","name":"谷歌"}
]',
'\\[|\\]' , ''), 將json數(shù)組兩邊的中括號去掉
'\\}\\,\\{' , '\\}\\;\\{'), 將json數(shù)組元素之間的逗號換成分號
'\\;') 以分號作為分隔符(split函數(shù)以分號作為分隔)
);
然后提取json對象中的屬性
select json_tuple(json, 'website', 'name')
from (
select explode(split(regexp_replace(regexp_replace('[{"website":"baidu.com","name":"百度"},{"website":"google.com","name":"谷歌"}]', '\\[|\\]',''),'\\}\\,\\{','\\}\\;\\{'),'\\;'))
as json) t;
?執(zhí)行上述語句,沒有報錯,執(zhí)行結(jié)果如下:
執(zhí)行上述語句,沒有報錯,執(zhí)行結(jié)果如下:
www.baidu.com 百度
google.com 谷歌
3.5 使用 lateral view 解析json數(shù)組
lateral view首先為原始表的每行調(diào)用UDTF,UDTF會把一行拆分成一行或者多行,lateral view在把結(jié)果組合,產(chǎn)生一個支持別名表的虛擬表。
nameid_listzhangsan[ 1,2,3 ]lisi[ 3,4,5 ]
對興趣id進行解析
SELECT name, hobby_id
FROM hobbies_table
LATERAL VIEW explode(id_list) tmp_table AS hobby_id;
上述sql執(zhí)行結(jié)果:
namehobby_idzhangsan1zhangsan2zhangsan3lisi3lisi4lisi5
假設(shè)有一張表如下:
hive 表中 goods_id 和json_str 字段的內(nèi)容如下:goods_idjson_str1,2,3[? {"source":"7fresh","monthSales":4900,"userCount":1900,"score":"9.9"},{"source":"jd","monthSales":2090,"userCount":78981,"score":"9.8"},{"source":"jdmart","monthSales":6987,"userCount":1600,"score":"9.0"}? ]
select good_id,get_json_object(sale_json,'$.monthSales') as monthSales
from tableName
LATERAL VIEW explode(split(goods_id,','))goods as good_id
LATERAL VIEW explode(split(regexp_replace(regexp_replace(json_str , '\\[|\\]',''),'\\}\\,\\{','\\}\\;\\{'),'\\;')) sales as sale_json;
笛卡爾集合
goods_idmonthSales149001209016987249002209026987349003209036987
四、內(nèi)置函數(shù)
4.1 NVL
給值為NULL的數(shù)據(jù)賦值,它的格式是NVL( value,default_value)。它的功能是如果value為NULL,則NVL函數(shù)返回default_value的值,否則返回value的值,如果兩個參數(shù)都為NULL ,則返回NULL
select nvl(column, 0) from xxx;
4.2 行轉(zhuǎn)列
函數(shù)描述CONCAT(string A/col, string B/col…)返回輸入字符串連接后的結(jié)果,支持任意個輸入字符串CONCAT_WS(separator, str1, str2,...)第一個參數(shù)參數(shù)間的分隔符,如果分隔符是 NULL,返回值也將為 NULL。這個函數(shù)會跳過分隔符參數(shù)后的任何 NULL 和空字符串。分隔符將被加到被連接的字符串之間。COLLECT_SET(col)將某字段的值進行去重匯總,產(chǎn)生array類型字段COLLECT_LIST(col)函數(shù)只接受基本數(shù)據(jù)類型,它的主要作用是將某字段的值進行不去重匯總,產(chǎn)生array類型字段。
4.3 列轉(zhuǎn)行(一列轉(zhuǎn)多行)
Split(str, separator):?將字符串按照后面的分隔符切割,轉(zhuǎn)換成字符array。
EXPLODE(col):將hive一列中復(fù)雜的array或者map結(jié)構(gòu)拆分成多行。
LATERAL VIEW
用法:
LATERAL VIEW udtf(expression) tableAlias AS columnAlias
解釋:lateral view用于和split, explode等UDTF一起使用,它能夠?qū)⒁恍袛?shù)據(jù)拆成多行數(shù)據(jù),在此基礎(chǔ)上可以對拆分后的數(shù)據(jù)進行聚合。
lateral view首先為原始表的每行調(diào)用UDTF,UDTF會把一行拆分成一或者多行,lateral view再把結(jié)果組合,產(chǎn)生一個支持別名表的虛擬表。
準備數(shù)據(jù)源測試
moviecategory《功勛》記錄,劇情《戰(zhàn)狼2》戰(zhàn)爭,動作,災(zāi)難
SQL
SELECT movie,category_name
FROM movie_info
lateral VIEW
explode(split(category,",")) movie_info_tmp AS category_name ;
測試結(jié)果
《功勛》 記錄
《功勛》 劇情
《戰(zhàn)狼2》 戰(zhàn)爭
《戰(zhàn)狼2》 動作
《戰(zhàn)狼2》 災(zāi)難
柚子快報邀請碼778899分享:hive sql 語句查詢規(guī)則
參考文章
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。