EAX
EAX

Reputation: 111

Group and sum multiple columns

Table with these columns:

id | name1 | score1 | name2 | score2

I need to transform the result of these two queries in one

SELECT name1, SUM(score1) as a
FROM partidos
GROUP BY name1
ORDER BY a DESC;

SELECT name2, SUM(score2) as b
FROM partidos
GROUP BY name2
ORDER BY b DESC;

The result is 'a + b', I need this sum and the name in one query.

Example:

id |   name1  |  score1  |   name2  |  score2
1  | james    | 5        | carolina | 3
2  | carolina | 3        | troll    | 9
3  | mordor   | 6        | ent      | 5
4  | carolina | 1        | paul     | 3
5  | paul     | 18       | kek      | 1

Result:

paul 21
troll 9
carolina 7
mordor 6
ent 5
james 5
kek 1

Upvotes: 1

Views: 1043

Answers (1)

Pரதீப்
Pரதீப்

Reputation: 93694

use UNION ALL to combine the Score1 and Score2 in a single column then do the SUM

select Name, SUM(Total)
from
(
SELECT name1 as Name, score1 as Total
FROM partidos
union all
SELECT name2, score2 as Total
FROM partidos
) A
GROUP BY Name

Upvotes: 1

Related Questions