我有一个下面格式的表。
我能够使用oracle SQL中的LAG函数将表转换为以下格式。
但是,我希望以这样一种方式创建此结果表,即对于状态为'ON'的行,to_date应该提供下一个'OFF'日期的日期。下面是它的外观。
我们如何在Oracle SQL中做到这一点?
我认为您需要带选项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