Hello.
There is a table of test results, each line contains information about how much a particular user has typed in a particular test.

id | user_id | test_id | result 1 | 1 | 1 | 15 2 | 3 | 1 | 10 3 | 1 | 2 | 5 4 | 3 | 3 | 5 5 | 2 | 1 | 10 6 | 1 | 3 | 10 

It is required to calculate the total result for all tests for each user, that is, to output (according to the example above) the following:

 user 1 = 30 user 2 = 10 user 3 = 15 

How do you count and derive it? Can I read directly in the sql query? Or, first collect the entire table into an array, and somehow further process it?

Or is it easier to create an additional table into which to add all the points scored by the user?

Thank you in advance.

  • @ Alexey Shimansky group by user_id gives out only one maximum (because desc, if asc, then minimum) value for each user, and hides the rest, or I misunderstood something - Alexander Vladimirovich

1 answer 1

 SELECT user_id, SUM(result) AS user_sum FROM `table` GROUP BY user_id 

GROUP BY - used to define groups of output lines to which the aggregate functions (COUNT, MIN, MAX, AVG and SUM) can be applied ... more information ... and docks