0

我需要对每个玩家的所有分数(hiscore)进行总和。

现在我可以对玩家 1 或玩家 2 求和。例如,在类别 7 中,玩家 1 是汤姆,而在类别 5 中,玩家 2 也是汤姆。结果应该是 Tom = 2+10 = 12 分。

SELECT SUM(subpoints) AS hiscore, player1_id, player2_id, FROM (
    SELECT COUNT(current_record)*2 AS subpoints, player1_id, player2_id FROM db WHERE category_id IN (7,8) GROUP BY player1_id
       UNION ALL
    SELECT COUNT(current_record)*10 AS subpoints, player1_id, player2_id FROM db WHERE category_id IN (1,2,3,4,5,6) GROUP BY player1_id
) AS hi
GROUP BY player1_id

样品表:

 category_id | player1 | player2 | subpoints |
-------------+---------+---------+-----------+
           7 |   Tom   |  Mike   |     2     |
           5 |  Peter  |  Tom    |    10     |
----------------------------------------------

最终结果应该是:

  Player | hiscore |
  -------+---------+
  Tom    |   12    |
  Mike   |    2    |
  Peter  |   10    |
4

1 回答 1

1

您可以先取消透视列,然后再聚合它:

select player, sum(subpoints) hiscore
from
(
  select category_id, player1 player, subpoints
  from db
  union all
  select category_id, player2 player, subpoints
  from db
) d
group by player;

请参阅SQL Fiddle with Demo

如果您将原始查询集成到其中,则代码将类似于:

select player, sum(subpoints) hiscore
from
(
  SELECT COUNT(current_record)*2 AS subpoints, player1_id as player
  FROM db 
  WHERE category_id IN (7,8) 
  GROUP BY player1_id
  UNION ALL
  SELECT COUNT(current_record)*10 AS subpoints, player2_id as player
  FROM db 
  WHERE category_id IN (1,2,3,4,5,6) 
  GROUP BY player2_id
) d
group by player
于 2013-05-09T14:13:46.530 回答