简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM