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

问题描述 投票:0回答:1

来源

所需输出

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

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

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

为了帮助您,我的日历表如下所示 日历

date hive formula hql impala
1个回答
0
投票

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

split(space(months_between(next_date, DT)),' ')
- 这将创建一个大小为
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 |
+----------+----------+

它将适用于任意数量的输入行,这只是您问题中的两个输入行的示例

© www.soinside.com 2019 - 2024. All rights reserved.