SQL将在两个不同列中按相同标识符分组的字段求和

时间:2012-05-18 00:21:53

标签: mysql sql

该表有4列Match,Winning_Player_ID,Losing_Player_ID,Quantity_Points_Exchanged_for_that_match。我想在一个查询中显示每个玩家在所有比赛中赢得和赢得的总分数。

这是表格

M WIN LOSE QTY  
1 100 201 10  
2 201 100 05  
3 100 201 05  
4 302 100 05  

对于输出,我希望在单个查询中以这种方式将其累加,并且无法弄清楚。

ID WIN LOSE
100 15 10
201 05 15
302 05 00

3 个答案:

答案 0 :(得分:1)

SELECT p.player ID,
       (SELECT SUM(QTY) FROM tbl WHERE WIN = p.player) WIN,
       (SELECT SUM(QTY) FROM tbl WHERE LOSE = p.player) LOSE
FROM
    (SELECT DISTINCT WIN player FROM tbl
    UNION
    SELECT DISTINCT LOSE FROM tbl) p

答案 1 :(得分:1)

没有数据库可以检查这个,但可能是这样的:

SELECT player, SUM(winQty) AS WIN, SUM(loseQty) AS LOSE
  FROM ( SELECT win AS player, qty AS winQty, 0 AS loseQty
           FROM myTable
         UNION ALL
         SELECT lose AS player, 0 AS winQty, qty AS loseQty
           FROM myTable
       ) x
  GROUP BY player

更新:将UNION更改为UNION ALL

答案 2 :(得分:0)

以下是答案:

创建表:

CREATE TABLE table_name (
  m int,
  win int,
  lose int,
  qty int);

插入数据:

INSERT INTO table_name (m, win, lose, qty)
values 
(1, 100, 201, 10),
(2, 201, 100, 05),
(3, 100, 201, 05),
(4, 302, 100, 05);

QUERY:

SELECT id, sum(won), sum(lost) from (
    SELECT win as id, SUM(qty) as won, 0 as lost 
    FROM table_name W GROUP BY win
  UNION
    SELECT lose as id, 0 as won, SUM(qty) as lost
    FROM table_name W GROUP BY lose
  ) sums
GROUP BY ID 

结果:

+------+----------+-----------+
| id   | sum(won) | sum(lost) |
+------+----------+-----------+
|  100 |       15 |        10 |
|  201 |        5 |        15 |
|  302 |        5 |         0 |
+------+----------+-----------+