简体   繁体   中英

mysql group by but only group if second row is the same

im wondering what the smartest way is to group my mysql results... I have the following table structure:

- id
- userId
- status (values from 1-100)

Lets say with the following content:

1 | 1 | 10
2 | 1 | 10
3 | 1 | 15
4 | 2 | 15
5 | 3 | 10

Now I want to group all results by user but only for each status. So the results im looking for should be:

1 | 1 | 10
3 | 1 | 15
4 | 2 | 15
5 | 3 | 10

Hope you understand want im looking for...

Best Tassilo

If you need the id, then a GROUPing query is needed; this will produce the results you shown:

SELECT MIN(id), userId, status
FROM your_table
GROUP BY userId, status
;

If you don't need the id, then GROUPing is not the best tool, use DISTINCT instead; like so:

SELECT DISTINCT userId, status
FROM your_table
;

The topic of this question say "Group only if next row is the same" in that case I would do something like this:

create table USER_(id integer, UserId integer, status integer);

insert into USER_ values(1,1,10);
insert into USER_ values(2,1,10);
insert into USER_ values(3,1,115);
insert into USER_ values(4,2,115);
insert into USER_ values(5,3,10);
insert into USER_ values(6,1,10);

select min(a.id)as id, a.userId, a.status ,count(*) from USER_ a join USER_ b 
on a.userid = b.userid and a.id = b.id-1 group by a.userId,a.status;

 id | userid | status | count 
-----+--------+--------+-------    
  1 |      1 |     10 |     2

If I look at the explanation for the question here then, I would do something like this:

select min(a.id) as id, a.userId, a.status  from USER_ a 
group by a.userId,a.status order by a.userid,status;

 id | userid | status 
----+--------+--------
  1 |      1 |    10
  3 |      1 |    15
  4 |      2 |    15
  5 |      3 |    10

Please correct if I have a wrong understanding of the question

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