Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!