postgresql given “1,2,3,6,7,8,11,12,15,18,19,20”, a query to return the maximum of each group of consecutive numbers

假如想象 提交于 2021-02-05 12:20:29

问题


given 1,2,3,6,7,8,11,12,15,18,19,20, write a query to return the maximum of each group of the consecutive numbers are grouped by the query below, but I don't know how to obtain the maximum for each group of consecutive numbers with my current query

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:


Assuming you want 3, 8, 12, 15, and 20, you would use 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;

This uses the observation that you can find the end number just by comparing the "next number" to the current value plus 1.

If you want these in a string:

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

Here is a db<>fiddle.



来源:https://stackoverflow.com/questions/62606818/postgresql-given-1-2-3-6-7-8-11-12-15-18-19-20-a-query-to-return-the-maximum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!