简体   繁体   中英

sum up frags and group teams with sql query

I have a table with two teams and frag counts

| id | teamA_name | teamA_frags | teamB_name | teamB_frags |
| 1  |     5      |     3       |     7      |     9       |
| 2  |     5      |     4       |     7      |     1       |
| 3  |     3      |     2       |     6      |     4       |
| 4  |     3      |     8       |     6      |     8       |

Is it possible to sum up all frags and present this data like that?

| team | frags |
|  5   |   7   |
|  7   |  10   |
|  3   |  10   |
|  6   |  12   |

EDIT 1 : I tried queries with group by and group concat, but they are not giving me the output I wanted. For example:

SELECT teamA_name, teamB_name, SUM(teamA_frags), SUM(teamB_frags) FROM Table;

This is summing up frags OK, but printing teams next to eachother. My knowledge of SQL is limited.

Basically, you need to unpivot and re-aggregate. Here is one approach:

select team, sum(frags)
from ((select teamA_name as team, teamA_frags as frags
       from t
      ) union all
      (select teamB_name as team, teamB_frags as frags
       from t
      )
     ) t
group by team;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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