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函数处理的内容投射到一张虚拟表上,我们就可以再对这个虚拟表进行各种操作了。

相关推荐
FungLeo1 小时前
FengCMS· PHP+MySQL升级实录 · 后台参数统一治理:id[]数组、id=undefined 跳转与312组回调组合
android·mysql·php·工程实践·fengcms
Flynn Liang3 小时前
AI Agent Redis 生产踩坑实录:13 类故障的根因、复现与调优
数据库·人工智能·redis·缓存·ai agent·故障分析
SelectDB4 小时前
开源日志平台怎么选?ELK、Loki、ClickHouse、Apache Doris 四大方案对比与选型指南
数据库
SelectDB4 小时前
ELK 磁盘空间不足怎么办?Elasticsearch 存储膨胀原因、排查步骤与 3 种降本方案
数据库
满小满4 小时前
为什么我先 ANALYZE,而不是先加索引
数据库·dba
SelectDB4 小时前
日志分析用什么数据库好?Elasticsearch、ClickHouse、Doris 选型对比与 3 个企业案例
数据库
inferno6 小时前
十三、存储过程(PROCEDURE)
数据库·sql·mysql
数据库急诊室_阿哲7 小时前
一周慢查询日志审计:1200 条里有多少真问题
运维·数据库·dba
zhangjw347 小时前
2-4 集合运算 union /union all /intersect/except
数据库·postgresql
Decay__8 小时前
PostgreSQL DBA 日常运维手册 —— 会话、锁阻塞、慢查询、膨胀与每日巡检
运维·数据库·sql·postgresql