Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.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
Postgres SQL分组依据,直到下一行不同_Sql_Postgresql_Max_Min_Gaps And Islands - Fatal编程技术网

Postgres SQL分组依据,直到下一行不同

Postgres SQL分组依据,直到下一行不同,sql,postgresql,max,min,gaps-and-islands,Sql,Postgresql,Max,Min,Gaps And Islands,我在博士后中有以下数据: index | item | ------+-------- 10 | aaa | 20 | aaa | 30 | bbb | 40 | aaa | 50 | aaa | 我想把它分组,得到最小值和最大值。但是,它只应分组,直到下一行是不同的项目 期望值: indexMin | indexMax | item | ---------+----------+---------- 10 | 20

我在博士后中有以下数据:

index | item  |
------+--------
  10  | aaa   |
  20  | aaa   |
  30  | bbb   |
  40  | aaa   |
  50  | aaa   |
我想把它分组,得到最小值和最大值。但是,它只应分组,直到下一行是不同的项目

期望值:

indexMin | indexMax | item    |
---------+----------+----------
  10     | 20       | aaa     |
  30     | 30       | bbb     |
  40     | 50       | aaa     |
  

这是一个间隙和孤岛问题,您希望将“相邻”行分组在一起。在这里,最简单的方法是使用行号之间的差异来标识组:

select min(idx) min_idx, max(idx) max_idx, item
from (
    select 
        t.*,
        row_number() over(order by idx) rn1,
        row_number() over(partition by item order by idx) rn2
    from mytable t
) t
group by item, rn1 - rn2
order by min(idx)