您需要将值为 150 的行拆分为两个单独的部分。您可以通过使用分析函数来做到这一点。该lead
函数允许您按某种顺序查看下一行的值。在这种情况下,您希望通过 fromdate 找到不同的值顺序:
select lead(value) over (order by fromdate) from tab;
然后,您可以将其与当前值进行比较以查看它们何时发生变化,并在它们发生变化时输出鉴别器:
select value, case when ld <> value or ld is null then rownum end c from (
select value, lead(value) over (order by fromdate) ld from tab
)
VALUE, C
-----------
150 null
150 null
150 3
120 null
120 5
150 null
150 7
然后,您需要“填写”鉴别器以替换空值。这可以通过分析再次完成,min
通过从日期降序选择鉴别器值。然后,您可以按此值分组以提供所需的输出:
select date1, value, d, min(fromdate), max(fromdate)
from (
select date1, fromdate, value,
--"fill down" the discriminator, so you can group by it at the next level
min(c) over (order by fromdate desc) d
from (
select date1, fromdate, value, ld,
--compare the next value with the current, if they're different
--show an indicator
case when value <> ld or ld is null then rownum else null end c
from (
select date1, fromdate, value,lead(value) over (order by fromdate) ld
from tab
)
)
)
group by date1, value, d