【Hive】生成动态日期序列

您所在的位置:网站首页 sql自动添加时间函数 【Hive】生成动态日期序列

【Hive】生成动态日期序列

2024-07-03 15:10| 来源: 网络整理| 查看: 265

一、问题描述

已知开始日期和结束日期,动态生成此范围内的日期序列。具体如下:

二、解决方案

1.原始表 test

create table test as select 'A' as id, '2019-01-07' as begin_date, '2019-01-10' as end_date union all select 'A' as id, '2019-01-01' as begin_date, '2019-01-04' as end_date union all select 'B' as id, '2019-01-03' as begin_date, '2019-01-05' as end_date

2.数据处理

(1)计算需要重复的行数n(天数n=结束日期end_date - 开始日期begin_date);

(2)设计一个长度为 n 的数组对象。通过 space(n)函数 生成 n 个空格的字符串,split()函数 以空格为分隔符,将字符串变成含 n 个元素的数组,根据此,这里也可以换成 split(repeat(n, 分隔符),分隔符);

(3)通过udtf函数 posexplode()函数 对数组字段进列转行,同时生成行号 i ;

(4)最后,根据每行的行号 i,以及开始日期begin_date计算当前日期current_date。

select id, date_add (begin_date, pe.i) as current_date, begin_date, end_date from test lateral view posexplode(split(space(datediff(end_date, begin_date)),' ')) pe as i, x -- space()函数可以换成repeat

[参考]

1.如何在HIVE中生成日期序列?https://xbuba.com/questions/45278300



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3