postgres给了我一组数字,例如“1,2,3,6,7,8,11,12,15,18,19,20” 获得每组连续数字的最大值

Posted

技术标签:

【中文标题】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 【发布时间】:2020-10-17 17:10:00 【问题描述】:

连续的数字按下面的查询分组,但我不知道如何获得每组连续数字的最大值

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;

【问题讨论】:

【参考方案1】:

R中,我们可以用diffcumsum创建一个组,然后用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)

【讨论】:

它应该在 postgresql 中 @gigi 我看到标签R 并回答了它

以上是关于postgres给了我一组数字,例如“1,2,3,6,7,8,11,12,15,18,19,20” 获得每组连续数字的最大值的主要内容,如果未能解决你的问题,请参考以下文章

现实给了我一巴掌 既不道歉,也不说话 用最好的年华,换最深刻的教训

[原创] Win7全自动精简批处理_绝对原创,绝对给力_感谢无忧给了我一年的潜水

scipy.spatial 中的凸壳例程给了我原来的一组点

使用一个查询递增具有唯一约束的字段中的一组值,Postgres

#419(div2) C. Karen and Game

如何使用 LINQ 从一组数字中查找 n 项的所有组合?