我需要为每个玩家做一个所有点(他的核心)的总和。
现在我能够将玩家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 |
答案 0 :(得分: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;
如果将原始查询集成到此中,则代码将类似于:
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