Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
postgresql给定的“;“1,2,3,6,7,8,11,12,15,18,19,20”;,返回每组连续数字的最大值的查询_Sql_Postgresql_Gaps And Islands - Fatal编程技术网

postgresql给定的“;“1,2,3,6,7,8,11,12,15,18,19,20”;,返回每组连续数字的最大值的查询

postgresql给定的“;“1,2,3,6,7,8,11,12,15,18,19,20”;,返回每组连续数字的最大值的查询,sql,postgresql,gaps-and-islands,Sql,Postgresql,Gaps And Islands,给定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(n

给定
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;

假设您想要3、8、12、15和20,您可以使用
lead()

这使用了这样一个观察结果,即只需将“下一个数字”与当前值加1进行比较,就可以找到结束数字

如果您希望这些内容以字符串形式出现:

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

是一个数字小提琴。

请澄清……
范围。high
是“每组连续数字的最大值”是,
范围。high
是每组的最大值。你已经有了。你还需要什么?
select string_agg(c1::text, ',' order by c1)