How to combine near same item by SQL?

后端 未结 6 691
既然无缘
既然无缘 2021-02-11 10:53

I have some data in database:

id user 
1 zhangsan 
2 zhangsan 
3 zhangsan 
4 lisi 
5 lisi 
6 lisi 
7 zhangsan 
8 zhangsan 

I want keep order, a

6条回答
  •  执念已碎
    2021-02-11 11:44

    If you try:

    SET @name:='',@num:=0;
    
    SELECT id,
           @num:= if(@name = user, @num, @num + 1) as number,
           @name := user as user
    FROM foo
    ORDER BY id ASC;
    

    This gives:

    +------+--------+------+
    | id   | number | user |
    +------+--------+------+
    |    1 |      1 | a    |
    |    2 |      1 | a    |
    |    3 |      1 | a    |
    |    4 |      2 | b    |
    |    5 |      2 | b    |
    |    6 |      2 | b    |
    |    7 |      3 | a    |
    |    8 |      3 | a    |
    +------+--------+------+
    

    So then you can try:

    SET @name:='',@num:=0;
    
    SELECT COUNT(*) as count, user
    FROM (
    SELECT @num:= if(@name = user, @num, @num + 1) as number,
           @name := user as user
    FROM foo
    ORDER BY id ASC
    ) x
    GROUP BY number;
    

    Which gives

    +-------+------+
    | count | user |
    +-------+------+
    |     3 | a    |
    |     3 | b    |
    |     2 | a    |
    +-------+------+
    

    (I called my table foo and also just used names a and b because I was too lazy to write zhangsan and lisi over and over).

提交回复
热议问题