MySQL: grouping only related strings

Is there a way in MySQL to group “only” connected (serialized) rows in a table:

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

Group by user_id and sum(score), but only for subsequent lines with the same user_id, the expected results:

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

Test request:

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

Will return something like:

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

thanks for reference

+4
source share
2 answers
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)
+2
source

Like mysql, add extra group byfor evaluations

select userid, sum(score)
from MyTable
group by userid, score

For downvoters check it out

-1
source

Source: https://habr.com/ru/post/1667744/


All Articles