简体   繁体   English

如何根据条件对不同行中的相同值进行 GROUP BY? (MYSQL)

[英]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:我想GROUP BY是这样的:

+-----------+-----------+---------------------+
| 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)但是当我放GROUP BY member_id时,它只返回两行 (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.我将其理解为一个差距和孤岛问题,您希望在其中显示其member_id与“上一个”行不同的行。

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:这是一种使用 window 函数(在 MySQL 8.0 中可用)的方法: lag()给出前一行的member_id ,然后我们可以将其与当前行的值进行比较:

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 : 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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