Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

PostgreSQL find consecutive continued integers in a list

I'm trying to find consecutive values from an unsorted list.

1 2 3 5 6 2

so the result is

1   [1-3]
2   [1-3]
2   [1-3]
3   [1-3]

5   [5-6]
6   [5-6]

So I'm find out some code may help

   select elem, min(elem) over wa as min_nr, max(elem) over wa as max_nr from (
    with the_data(arr) as (
    values (array[5,2,2,10,8,3,7,9,20,21,25])
    )
    
    select elem, sum(diff) over w as group_nr
    from (
        select elem, (elem- 1 is distinct from lag(elem) over w)::int as diff
        from the_data, unnest(arr) as elem
        window w as (order by elem)
        ) s
    window w as (order by elem)
   ) aa
  window wa AS (PARTITION BY group_nr ORDER BY group_nr);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...