根据其他日期字段的间隔更新日期字段

时间:2018-10-12 21:19:38

标签: sql window-functions greenplum

我有以下字段:

   implement_dt    approval_dt    phase
    3/31/2018      12/31/2017       1
    3/31/2019      12/31/2017       2
    3/31/2020      12/31/2017       3

我正尝试根据approval_dt的间隔重新计算implement_dt到:(而且我不能仅仅将相位添加到approval_dt,因为某些间隔更大超过一年)

   implement_dt    approval_dt    phase
    3/31/2018      12/31/2017       1
    3/31/2019      12/31/2018       2
    3/31/2020      12/31/2019       3

我基本上已经使用以下代码做到了这一点:

select *
, case when phase = 1 then approval_dt
       when phase > 1 then approval_dt + balance
       else null
       end as new_date       
from (
select *
, sum(changes) over (order by phase) as balance
from (
select *
, implement_dt - lag(implement_dt) over (order by phase) as changes
from chk1
) x
) y
;

此功能有效,除非a年的approval_dt12/31。使用上面的代码,我的结果是:

   implement_dt    approval_dt    phase
    3/31/2018      12/31/2017       1
    3/31/2019      12/31/2018       2
    3/31/2020       1/1/2020        3

3/31/20193/31/2020之间的天数差为366天。我需要1/1/202012/31/2019

我已经尝试过使用implement_dt之间的年份差异而不是天数,并将其乘以365以获得“纯净年份”的变体,但是在第3行中却不断出现错误:

select *
, case when phase = 1 then approval_dt
       when phase > 1 then approval_dt + balance
       else null
       end as new_date       
from (
select *
, (sum(changes) over (order by phase)::bigint)*365 as balance
from (
select *
, extract(year from implement_dt) - lag(extract(year from implement_dt)) over (order by phase) as changes
from chk1
) x
) y
;

ERROR:  operator does not exist: date + bigint
LINE 3:        when phase > 1 then approval_dt + balance
                                               ^
HINT:  No operator matches the given name and argument type(s). You may need to add explicit type casts.

我在Greenplum中将pgAdmin与PostgreSQL一起使用。有什么建议吗?

0 个答案:

没有答案
相关问题