【问题标题】:How can I get the information from the following row and fill if there is no information?如果没有信息,如何从下一行获取信息并填写?
【发布时间】:2020-10-09 18:22:17
【问题描述】:

所以我有下表:

Id     Billing_Date
A00    2020-01-01
A00    2020-02-01
A00    2020-04-01
B91    2020-01-01
B91    2020-03-01
B91    2020-04-01
C11    2020-01-01 

我想要做的是从下一行获取日期,如果我没有找到这个日期,那么我将填写 Billing_Date + 60 天。当然,一切都基于 Id。这就是我的数据最终应该是什么样子:

Id     Billing_Date    Billing_Date_Duo
A00    2020-01-01      2020-02-01
A00    2020-02-01      2020-04-01
A00    2020-04-01      2020-06-01
B91    2020-01-01      2020-03-01
B91    2020-03-01      2020-04-01
B91    2020-04-01      2020-06-01
C11    2020-01-01      2020-03-01

我该怎么做?我知道我应该使用 lead() 之类的东西,但不确定如何在此处执行此操作以及如何与 case when 结合使用。

我认为这会起作用,但它没有:

select Id, Billing_Date, 
    lead(Billing_Date) over (order by Id) as Billing_Date_Duo

【问题讨论】:

    标签: sql postgresql date select window-functions


    【解决方案1】:

    您可以在正确的分区上使用lead() (id) 和order by,以及coalesce() 来分配默认值:

    select
        id,
        billing_date,
        coalesce(
            lead(billing_date) over(partition by id order by billing_date),
            billing_date + interval '60 day'
        ) billing_date_duo
    from mytable
    

    您可以使用 lag() 的 3-form 参数来缩短它:

    select
        id,
        billing_date,
        lead(billing_date, 1, (billing_date + interval '60 day')::date) 
            over(partition by id order by billing_date) billing_date_duo
    from mytable
    

    Demo on DB Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 2018-04-29
      相关资源
      最近更新 更多