【问题标题】:Oracle SQL: Restart sequence based on rowOracle SQL:基于行的重启顺序
【发布时间】:2020-11-19 09:37:30
【问题描述】:

我的数据集如下:

**series**
start
continue
continue
end
start
continue
end

我需要添加一个列,该列包含一个序列 ('leftijd_seq'),该序列从“开始”开始,在“继续”处递增 1,并在“结束”处结束。我尝试了下面的代码,但我的执行语句不适用于我创建的序列。

SELECT batchnr, series,
  CASE WHEN series = 'start' THEN execute 'alter sequence leeftijd_seq restart start with 1;' and leeftijd_seq.nextval
    when series = 'continue' then leeftijd_seq.nextval
    ELSE leeftijd_seq.currval
    END SEQ_NO
FROM data order by batchnr asc

【问题讨论】:

  • 如果有一个“end”后面不是“start”,而是“continue”,例如,你想要哪种行为?

标签: sql oracle sequence gaps-and-islands


【解决方案1】:

这听起来像是一个空白和孤岛问题。我建议建立组的“开始”窗口计数:

select t.*,
    row_number() over(partition by grp order by batchnr) as seq_no
from (
    select t.*,
        sum(case when series = 'start' then 1 else 0 end) over(order by batchnr) as grp
    from mytable t
) t

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多