在 Hive 查询 (HQL) 中创建两个日期之间的日期,以后需要进一步转换

Create dates between two dates in Hive query(HQL) and later needs further transformation

提问人:Saumya Shah 提问时间:11/8/2023 最后编辑:leftjoinSaumya Shah 更新时间:11/10/2023 访问量:51

问:

enter image description here

所需输出enter image description here

我想要的输出是 D 列和 C 列。 公式列是为了帮助您了解我如何进行计算。 我首先尝试根据最小日期和最大日期分解日期。这是我做不到的。

我还尝试将源表连接到主 calednar 表。但我也无法过滤到所需的输出。

Select Distinct mc.D, src.A From db.calendar mc LEFT JOIN db.source src ON mc.D= src.D;

为了您的帮助,我的日历表如下所示 日历enter image description here

sql 日期 配置单元 公式 impala

评论


答:

0赞 leftjoin 11/10/2023 #1

这将在 Hive 中起作用,而不是 Impala,因为 Impala 不支持 .或者,也许最新的 Impala 支持使用连接生成分解和行,请查看有关 Impala 的答案lateral view posexplode

这是 Hive 的解决方案。

您不需要日历,因为可以使用以下方法生成缺少的日期:

split(space(months_between(next_date, DT)),' ')- 这将创建一个 size =months_between(next_date, DT)

posexplode()将分解数组并生成提供索引 i 的行(从 0 开始)

然后使用索引和稍微修改的公式,您可以计算缺失的日期和金额。查看演示:i

with Source as (--source data, will work with more input dates
select '2023-06-30' as DT, 131234 as Amount union all
select '2023-12-31', 1243435 
) 

select last_day(add_months(DT, i)) as `Date`, --calculate date as start date+i (position from posexplode starts w 0)
       round(Amount + ((next_amount-Amount)/months_between(next_date, DT))*i,2) as Amount --formula
from
( --Get next_date to generate date range
select DT, Amount,
       lead(DT,1) over (order by DT) next_date,
       lead(Amount,1) over (order by DT) next_amount
  from Source s  
)s lateral view posexplode(split(space(months_between(next_date, DT)),' ')) e as i,x --generate rows

结果:

+----------+----------+
|Date      |Amount    |
+----------+----------+
|2023-06-30|131234.0  |
|2023-07-31|316600.83 |
|2023-08-31|501967.67 |
|2023-09-30|687334.5  |
|2023-10-31|872701.33 |
|2023-11-30|1058068.17|
|2023-12-31|1243435.0 |
+----------+----------+