postgres 我得到了一组数字,如“1,2,3,6,7,8,11,12,15,18,19,20”获得每组连续数字的最大值
postgres I was given a set of number like "1,2,3,6,7,8,11,12,15,18,19,20" obtain maximum of each group consecutive numbers
下面的查询对连续的数字进行了分组,但是我不知道如何获取每组连续数字的最大值
with trans as (
select c1,
case when lag(c1) over (order by c1) = c1 - 1 then 0 else 1 end as new
from table1
), groups as (
select c1, sum(new) over (order by c1) as grpnum
from trans
), ranges as (
select grpnum, min(c1) as low, max(c1) as high
from groups
group by grpnum
), texts as (
select grpnum,
case
when low = high then low::text
else low::text||'-'||high::text
end as txt
from ranges
)
select string_agg(txt, ',' order by grpnum) as number
from texts;
在R
中,我们可以用diff
和cumsum
创建一个组,然后用tapply
得到向量的max
每组
grp <- cumsum(c(TRUE, diff(v1) > 1))
tapply(v1, grp, FUN = max)
# 1 2 3 4 5
# 3 8 12 15 20
数据
v1 <- c(1, 2, 3, 6, 7, 8, 11, 12, 15, 18, 19, 20)
下面的查询对连续的数字进行了分组,但是我不知道如何获取每组连续数字的最大值
with trans as (
select c1,
case when lag(c1) over (order by c1) = c1 - 1 then 0 else 1 end as new
from table1
), groups as (
select c1, sum(new) over (order by c1) as grpnum
from trans
), ranges as (
select grpnum, min(c1) as low, max(c1) as high
from groups
group by grpnum
), texts as (
select grpnum,
case
when low = high then low::text
else low::text||'-'||high::text
end as txt
from ranges
)
select string_agg(txt, ',' order by grpnum) as number
from texts;
在R
中,我们可以用diff
和cumsum
创建一个组,然后用tapply
得到向量的max
每组
grp <- cumsum(c(TRUE, diff(v1) > 1))
tapply(v1, grp, FUN = max)
# 1 2 3 4 5
# 3 8 12 15 20
数据
v1 <- c(1, 2, 3, 6, 7, 8, 11, 12, 15, 18, 19, 20)