在特定条件下使用LAG函数

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

我有一个下面格式的表。

enter image description here

我能够使用oracle SQL中的LAG函数将表转换为以下格式。

enter image description here

但是,我希望以这样一种方式创建此结果表,即对于状态为'ON'的行,to_date应该提供下一个'OFF'日期的日期。下面是它的外观。

enter image description here

我们如何在Oracle SQL中做到这一点?

sql oracle lag
2个回答
0
投票

我认为您需要带选项lead()的条件ignore nulls

select 
    id,
    date from_date,
    case when status = 'ON' 
        then lead(case when status = 'OFF' then date end ignore nulls) 
            over(partition by id order by date)
    end
from mytable

为了更好地匹配预期结果,我们将该功能应用于'OFF'以外的任何状态,并从结果中撤回1天:

select 
    id,
    date from_date,
    case when status <> 'OFF' 
        then lead(case when status = 'OFF' then date end ignore nulls) 
            over(partition by id order by date) - 1
    end
from mytable

如果您还想要'ON'行的下一个'OFF'日期:

select 
    id,
    date from_date,
    case when status <> 'OFF' 
        then lead(case when status = 'OFF' then date end ignore nulls) 
            over(partition by id order by date) - 1
        else lead(case when status = 'ON' then date end ignore nulls) 
            over(partition by id order by date) - 1
    end
from mytable
© www.soinside.com 2019 - 2024. All rights reserved.