hive sql 遇到的一些函数使用

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

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

test表
id bigint
name varchar(256)
age int

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字段中存储的值都是如下格式:

html 复制代码
{
    "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表
id name
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 要与UDTF(user defined table-generating functions)函数一起使用,这里的udft用上面的explode举例,lateral view 会将utdf函数应用到每一行上,经utdf处理后得到多行输出组建成一张虚拟表。

还是这张表:

test表
id name
1 小明,小红
2 小王

SELECT id, name

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

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

相关推荐
代码老y7 分钟前
穿透、误伤与回环——Redis 缓存防御体系的负向路径与治理艺术
数据库·redis·缓存
Themberfue12 分钟前
Redis ①⑥-缓存
数据库·redis·adb·缓存
Kyln.Wu12 分钟前
【python实用小脚本-139】Python 在线图片批量下载器:requests+PIL 一键保存网络图像
数据库·python·php
fengye2071612 小时前
板凳-------Mysql cookbook学习 (十一--------10)
学习·mysql·adb
李元豪2 小时前
grpo nl2sql qwen3 模型强化学习训练有效果的成立条件有哪些
数据库·oracle
Hello.Reader5 小时前
RedisJSON 路径语法深度解析与实战
数据库·redis·缓存
TDengine (老段)6 小时前
TDengine 使用最佳实践(2)
大数据·数据库·物联网·时序数据库·iot·tdengine·涛思数据
设计师小聂!9 小时前
Linux系统中部署Redis详解
linux·运维·数据库·redis
kfepiza9 小时前
Debian-10编译安装Mysql-5.7.44 笔记250706
linux·数据库·笔记·mysql·debian·bash
Touper.9 小时前
Redis 基础详细介绍(Redis简单介绍,命令行客户端,Redis 命令,Java客户端)
java·数据库·redis