hive sql 遇到的一些函数使用-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

1. cast(字段 as 需要转化为的类型)

举例有一个test表其中有三个字段

test表
idbigint
namevarchar(256)
ageint

select cast(age as bigint) as col1 from test limit  100;

查询的SQL中使用了cast(age as int)表示我将表中原本类型为int的值转为bigint类型类似于强制类型转换

注从Hive0.12.0开始支持varchar

2. get_json_object(字段, '$.字段的字段')或get_json_object(字段, '$.字段的字段[i]')

举例还是test表现在有四个字段

其中introduce字段中存储的值都是如下格式

{
    "col1":"hello world",
    "col2":[1,2],
    "col3":{
        "col31":"key1",
        "col32":"key2"
    }
}

单层select get_json_object(introduce, '$.col1') from test;

解释其中get_json_object(introduce, '$.col1')表示从introduce字段中取出名为col1对应的值即"hello world"

嵌套select get_json_object(introduce, '$.col3.col31') from test;

解释其中get_json_object(introduce, '$.col3.col31')表示从introduce字段中取出名为col3中col31对应的值即"key1"

数组select get_json_object(introduce, '$.col2[1]') from test;

解释其中get_json_object(introduce, '$.col2[1]')表示从introduce字段中取出名为col2数组中第二个值即1

3. date_format(FROM_UNIXTIME(表的某个数值必须是秒级别), '要求转为的格式')

举例test表现在有两个字段

time_stamp存储了秒级别的时间戳如果是bigint存储了毫秒级别的时间戳将值/1000转为秒级别即可

select cast(date_format(FROM_UNIXTIME(time_stamp), 'yyyyMM') as int) as day from test;

解释其中FROM_UNIXTIME会将时间由数字转为日期然后使用date_format将该日期转为'yyyyMM'类型的数据最后使用cast将该字段类型转为int。

4. replace(进行操作的字段, '字段中需要被替换的部分', '替换后的部分')

举例test表现在有两个字段

select replace(name, '·', '') as rep from test

解释将test表中的name字段中·全部替换掉。

5. split(需要被拆分成数据的字段, '字段被拆分成array的中间点')

举例test表现在有两个字段

select split(name, '!') as arr from test

解释如果name字段中的值有【!】比如【hello!world】那么会被拆成一个包含有两个值的array["hello", "world"]

6. explode(需要被行转列的array)

还是上面的例子现在的表具体为

test表
idname
1小明,小红
2小王

select id, explode(split(name, ',')) as exp from test

执行后为

 解释explode函数会将一个array或是map从一行拆为多行即由行转列

注仅使用explode的局限

  1. 不能关联原有的表中的其他字段。
  2. 不能与group by、cluster by、distribute by、sort by联用。
  3. 不能进行UDTF嵌套。
  4. 不允许选择其他表达式。

7. lateral view udtf函数 tableAlias AS columnAlias

lateral view 要与UDTFuser defined table-generating functions函数一起使用这里的udft用上面的explode举例lateral view 会将utdf函数应用到每一行上经utdf处理后得到多行输出组建成一张虚拟表。

还是这张表

test表
idname
1小明,小红
2小王

SELECT id, name
FROM test LATERAL VIEW explode(split(name, ',')) test_demo AS exp;

解释 LATERAL VIEW会将经过UDTF函数处理的内容投射到一张虚拟表上我们就可以再对这个虚拟表进行各种操作了。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

“hive sql 遇到的一些函数使用-CSDN博客” 的相关文章