【问题标题】:PostgreSQL query: write a query to return the maximum of each group of consecutive numbers [duplicate]PostgreSQL查询:编写查询返回每组连续数字的最大值[重复]
【发布时间】:2020-06-27 20:45:32
【问题描述】:

给定一组数字,例如“1,2,3,6,7,8,11,12,15,18,19,20”,编写一个查询以返回每组连续数字的最大值。

需要先找出哪些数字应该在一个组中,然后在每个组中找到最大值。

create table tt (c1 numeric);
insert into tt values
(1),(2),(3),(6),(7),(8),(11),(12),(15),(18),(19),(20);

所以答案是 3、8、12、15、20

【问题讨论】:

  • 你想要哪个结果?

标签: sql postgresql select window-functions gaps-and-islands


【解决方案1】:

我会将您的问题改写为:获取下一个值不按顺序排列的数字。如果是这样,您可以使用窗口函数:

select *
from (select c1, lead(c1) over(order by c1) lead_c1 from tt) t
where lead_c1 <> c1 + 1

对于您的示例数据,this produces

c1 |铅_c1 -: | ------: 3 | 6 8 | 11 12 | 15 15 | 18

如果您还想捕获最后一条记录(显然没有追随者),您可以将where 子句更改为:

where lead_c1 <> c1 + 1 or lead_c1 is null

【讨论】:

    【解决方案2】:

    我无法以duplicate 的身份结束这个问题,但我可以在此处复制我的答案: 假设您想要 3、8、12、15 和 20,您将使用 lead():

    select c1
    from (select t.*, lead(c1) over (order by c1) as next_c1
          from table1 t
         ) t
    where next_c1 is distinct from c1 + 1;
    

    这使用了观察,您可以通过将“下一个数字”与当前值加 1 进行比较来找到结束数字。

    如果你想把这些放在一个字符串中:

    select string_agg(c1::text, ',' order by c1)
    

    Here 是一个 dbfiddle。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-29
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      • 2022-07-19
      相关资源
      最近更新 更多