简体   繁体   English

分组和汇总多列

[英]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. 结果是' a + b ',我需要在一个查询中加上这个和和名称。

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

use UNION ALL to combine the Score1 and Score2 in a single column then do the SUM 使用UNION ALLScore1Score2合并到一个列中,然后执行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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM