PostgreSQL 在列表中查找连续的连续整数

时间:2021-01-07 06:20:49

标签: postgresql

我正在尝试从未排序的列表中查找连续值。

<块引用>

1 2 3 5 6 2

结果是

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

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

所以我发现一些代码可能有帮助

   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);

0 个答案:

没有答案