MySQL:仅按连接的行

时间:2017-01-25 09:42:55

标签: mysql sql

MySQL是否有办法按"仅#34;表中的连接(序列化)行:

ex,table:

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(score)但仅适用于具有相同" 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

谢谢,求助,

2 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:-1)

因为它是mysql,所以为分数增加id - description - title - id - user - authent - rel_id 1 - des1 - tit1 - 6 - admin - 4 - 5 2 - des2 - tit2 - null - null - null - null

group by

对于downvoters,check it