给定一个不同的有序整数数组,我希望取消数组,并为每一批连续整数分配一个组号。
{2,3,5,7,8,9,10,20,21,25}应返回
elem | group_nr
-----+---------
2 | 1
3 | 1
5 | 2
7 | 3
8 | 3
9 | 3
10 | 3
20 | 4
21 | 4
25 | 5发布于 2017-10-19 15:41:50
使用窗口函数 lag()和sum()
with the_data(arr) as (
values (array[2,3,5,7,8,9,10,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);
elem | group_nr
------+----------
2 | 1
3 | 1
5 | 2
7 | 3
8 | 3
9 | 3
10 | 3
20 | 4
21 | 4
25 | 5
(10 rows) 发布于 2017-10-19 15:40:31
取消嵌套后使用lag获取当前和上一行值的差异,然后使用运行和分配组号。
select id,num,sum(col) over(partition by id order by num) as grp
from (select id,num,case when num-lag(num,1,0) over(partition by id order by num)=1 then 0 else 1 end as col
from (select id,unnest(array_column) as num from tbl) t
) thttps://stackoverflow.com/questions/46833454
复制相似问题