Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
Postgres SQL Group By Until Next Row Different

I have following data in postgres:

index | item  |
------+--------
  10  | aaa   |
  20  | aaa   |
  30  | bbb   |
  40  | aaa   |
  50  | aaa   |

I would like to group it and get the minimum and maximum value. However, it only should group until next row is different item.

Expectation:

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

Can guide on this?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

This is a gaps-and-islands problem, where you want to group together "adjacent" rows. Here, the simplest approach is to use the difference between row numbers to identify the groups:

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)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda