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

320
Views
How to GROUP BY same value in different rows with condition? (MYSQL)

I have this table:

+-----------+-----------+---------------------+
| id        | member_id | date                |
+-----------+-----------+---------------------+
| 1         |     2     | 2020-07-27 21:53:46 |
| 2         |     1     | 2020-07-27 22:03:58 |
| 3         |     1     | 2020-07-27 22:09:16 |
| 4         |     1     | 2020-07-27 22:11:33 |
| 5         |     2     | 2020-07-27 22:12:21 |
-----------------------------------------------

And I would like to GROUP BY something like this:

+-----------+-----------+---------------------+
| id        | member_id | date                |
+-----------+-----------+---------------------+
| 1         |     2     | 2020-07-27 21:53:46 |
| 2         |     1     | 2020-07-27 22:03:58 |
| 5         |     2     | 2020-07-27 22:12:21 |
-----------------------------------------------

But when I put GROUP BY member_id it just return me two rows (1, 2)

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I understand this as a gaps-and-island problem, where you want to display the rows whose member_id is different than the "previous" row.

Here is an approach using window functions (available in MySQL 8.0): lag() gives the member_id on the previous row, that we can then compare to the value on the current row:

select id, member_id, date
from (
    select t.*, lag(member_id) over(order by date) lag_member_id
    from mytable t
) t
where not lag_member_id <=> member_id 
order by date

Demo on DB Fiddlde:

id | member_id | date               
-: | --------: | :------------------
 1 |         2 | 2020-07-27 21:53:46
 2 |         1 | 2020-07-27 22:03:58
 5 |         2 | 2020-07-27 22:12:21
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!