MySQL连接列并计数同一表中的值

时间:2018-12-10 11:54:09

标签: mysql sql

我有一张下表

| id | p1_name | p1_score | p2_name | p2_score |
------------------------------------------------
|  1 | aaa     | 2        | bbb     | 3        |
|  1 | ccc     | 1        | ddd     | 7        |
|  1 | ddd     | 5        | aaa     | 8        |

我需要计算所有球员的所有得分并以更简单的形式显示出来,就像这样:

| name | score |
----------------
| aaa  |  10   |
| bbb  |   3   |
| ccc  |   1   |
| ddd  |  12   |

实现此目标的SQL语法是什么?

2 个答案:

答案 0 :(得分:1)

使用Union All进行分组:

select q.name , sum(q.score) as score
  from
    (
    select p1_name as name, p1_score as score
      from tab
    union all 
    select p2_name as name, p2_score
      from tab
    ) q
group by q.name;  

Rextester Demo

答案 1 :(得分:0)

我们可以使用UNION ALL将名称与相应的分数值组合到一栏中。现在,我们可以将此结果集用作派生表,并在GROUP BY上使用name并获得分数的SUM()

SELECT 
  dt.name, 
  SUM(dt.score) AS score
FROM 
(
  SELECT
    p1_name AS name, 
    p1_score AS score
  FROM your_table
  UNION ALL
  SELECT
    p2_name AS name, 
    p2_score AS score
  FROM your_table
) AS dt
GROUP BY dt.name 

结果

| name | score |
| ---- | ----- |
| aaa  | 10    |
| bbb  | 3     |
| ccc  | 1     |
| ddd  | 12    |

View on DB Fiddle