Hive常用函数

163 阅读2分钟

假设现在有一个订单表(order),里面有3个字段:uid、item_id(商品id)、price、ts(时间戳)

uiditem_idpricets
u1i1101644503781
u2i2151644504880
u3i3201644503984

时间函数

将时间戳转化为可阅读的字符串

select from_unixtime(ts, 'yyyyMMdd HH:mm:ss'from order
--结果:
--20220210 22:36:21
--20220210 22:54:40
--20220210 22:39:44

将日期转化为时间戳

select unix_timestamp('20220209''yyyyMMdd');

计算日期差值,如过滤出距离2022.02.09 7天的订单(需要注意日期的格式)

select * from order where datediff('2022-02-09', from_unixtime(ts, 'yyyy-MM-dd')) <7

集合函数

计算集合大小

select size(array(1,2,3,4)); --结果: 4  

获取map中的key

select map_keys(map('a',1,'b',2,'c',3)); --结果: ["a","b","c"]

获取map中的取值

select map_keys(map('a',1,'b',2,'c',2)); --结果: [1,2,2]

判断数组中是否包含某个值

select array_contains(array(1,2,3,4), 4); --结果: true

数组排序

select sort_array(array(3,2,1,4)); --结果: [1,2,3,4]

拼接为字符串

select concat_ws('_'array('a''b''c')); --a_b_c

字符串函数

json解析

select get_json_object('{"name":"xyz"}''$.name'); --xyz

大小写转化

select lower('xYz'); --xyz
select upper('xYz'); --XYZ

条件函数

if条件

select
    if(id is null, 0idas id
from
    (
        select
            1 as id
        union all
        select
            null as id
    )

case when

select
    case
        when item_id = 'i1' then 1
        else 0
    end as item_str
from
    order

填充缺失值(nvl)

select
    nvl(id0as id
from
    (
        select
            1 as id
        union all
        select
            null as id
    )

取第一个不为null的值,否则为null

select coalesce(1null); -- 1
select coalesce(null2); -- 2
select coalesce(nullnull3); -- 3

杂项

数据类型转化

select cast('123' as int);

单行转多行

select explode(array(1,2,3));
--结果:
--1
--2
--3

原文地址:codelibrary.tech/2022/02/09/…