MySQL:仅按连接行分组


MySQL中是否有一种方法可以通过表中的“仅”连接(序列化)行进行分组:

表,:

id     user_id     score
1         1        100
2         1        100
3         2        100
5         1        100
7         1        100
8         3        100
9         4        100
10        5        100
10        5        100
11        1        100

按“user_id”和sum(得分)分组,但仅适用于具有相同“user_id”的后续行,预期结果:

user_id     score
    1        200
    2        100
    1        200
    3        100
    4        100
    5        200
    1        100

测试查询:

select t.user_id,sum(t.score)
from table t
group by t.user_id 

将返回如下内容:

user_id     score
    1        500
    2        100
    3        100
    4        100
    5        200

谢谢,求救

最佳答案

MariaDB [sandbox]> select user_id,sum(score) score
    -> from
    -> (select user_id,score,
    ->  if(user_id <> @p , @block:=@block+1,@block:=@block) block,
    ->  @p:=user_id
    -> from(select @block:=0,@p:=0) vars, t
    -> order by id,user_id
    -> ) s
    -> group by block
    ->  ;
+---------+-------+
| user_id | score |
+---------+-------+
|       1 |   200 |
|       2 |   100 |
|       1 |   200 |
|       3 |   100 |
|       4 |   100 |
|       5 |   200 |
|       1 |   100 |
+---------+-------+
7 rows in set (0.13 sec)
点赞