Hive函数说明

官网地址:
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF

下面列举几个有意思的函数

1. stack(int r,T1 V1,...,Tn/r Vn)
Breaks up n values V1,...,Vn into r rows. Each row will have n/r columns. r must be constant.
是一个udtf函数。即分解n个值V1…Vn转化成r行。每一行将有n/r列(向上取整)。R必须是常数。
例子:表t3
id    c1           c2         c3
1    c_v11    c_v21    c_v31
2    c_v12    c_v22    c_v32
select id,stack(3,"c1",c1,"c2",c2,"c3",c3) from t3;
就会输出:
id      col0     col1
1       c1      c_v11
1       c2      c_v21
1       c3      c_v31
2       c1      c_v12
2       c2      c_v22
2       c3      c_v32
但是要注意上面的sql写法在sparksql里可以,但是在hive sql里不行,会报错:
UDTF's are not supported outside the SELECT clause, nor nested in expressions
原因:当使用UDTF函数的时候,hive只允许对拆分字段进行访问。
即只能select stack(3,"c1",c1,"c2",c2,"c3",c3) from t3;
但是如果想要访问除了拆分字段以外的字段(比如上面的id字段),该如何做呢?
用lateral view侧视图。lateral view为了配合UDTF来使用,把某一行数据拆分成多行数据.不加lateral view的UDTF只能提取单个字段拆分,并不能放回原来数据表中。加上lateral view就可以将拆分的单个字段数据与原始表数据关联上。
使用方法:
表名 lateral view UDTF(xxx) 视图别名 as c1,c2..
即:
select id,subview.* from t3 lateral view stack(3,"c1",c1,"c2",c2,"c3",c3) subview
没有列名的默认返回col0,col1...
这里也可以指定列别名
select id,subview.* from t3 lateral view stack(3,"c1",c1,"c2",c2,"c3",c3) subview as cc1,cc2

2. collect_list(col)
Returns a list of objects with duplicates. 
是个udaf函数,返回给定列的集合,返回值是个array。还有collect_set(col)函数,唯一区别是这个是去重后的。

3. cast(expr as <type>)
Converts the results of the expression expr to <type>. For example, cast('1' as BIGINT) will convert the string '1' to its integral representation. A null is returned if the conversion does not succeed. If cast(expr as boolean) Hive returns true for a non-empty string.
是个类型转换函数。将expr表达式转换成type类型,如果转换失败将返回NULL
例子:
cast("1" as BIGINT) 将字符串1转换成了BIGINT类型

4. CASE WHEN a THEN b [WHEN c THEN d]* [ELSE e] END
When a = true, returns b; when c = true, returns d; else returns e.
是个条件函数。即a=true则返回b,或c=true则返回d,否则返回e。

5. concat_ws(string SEP, string A, string B...)或concat_ws(string SEP, array<string>)
是个字符串函数。即将字符串按分隔符SEP连接起来

6. greatest(T v1, T v2, ...)
Returns the greatest value of the list of values (as of Hive 1.1.0). Fixed to return NULL when one or more arguments are NULL, and strict type restriction relaxed, consistent with ">" operator (as of Hive 2.0.0).
是个数学函数,求取给定值中最大的一个,注意如果有NULL存在,则回返回NULL。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值