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, '$.col21') from test;

解释:其中get_json_object(introduce, '$.col21')表示从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函数处理的内容投射到一张虚拟表上,我们就可以再对这个虚拟表进行各种操作了。

相关推荐
摇滚侠9 小时前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
麦聪聊数据10 小时前
数据服务化时代:企业数据能力输出的核心路径
数据库
ApacheSeaTunnel11 小时前
实战演示 | 基于 Apache SeaTunnel 与 Apache DolphinScheduler 实现 MySQL 到 Doris 离线定时增量同步
大数据·mysql·开源·doris·数据集成·seatunnel·数据同步
shushangyun_11 小时前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
DARLING Zero two♡11 小时前
【MySQL数据库】数据类型与表约束
数据库·mysql
曹牧11 小时前
Oracle EXPLAIN PLAN
数据库·oracle
BD_Marathon12 小时前
SQL学习指南——视图
数据库·sql
活宝小娜12 小时前
mysql详细安装教程
数据库·mysql·adb
贤时间12 小时前
codex 助力oracle ebs 开发
数据库·oracle
秉承初心12 小时前
PostgreSQL 数据性能瓶颈突破实战
数据库·postgresql·oracle