SQL 计数两列并相减

SQL count two columns and substract

晚安。我遇到了这个问题,我尝试了子查询和案例但没有成功。

当玩家在我的游戏中杀人时,数据库中会添加一条新记录,这条记录包含杀手的 ID 和被杀死的玩家的 ID,所以过一会儿 table 会变成这样这个:

killer_id  |  death_id
100        |  200        -> (Player 100 Killed player 200)
100        |  200
100        |  200
200        |  100
300        |  100
300        |  200

我试图根据他们的击杀数减去他们的死亡数来计算每个玩家的分数,因此根据以上数据:

Rank:
Pos 1. player 300 / 2 Points  (2 Kills - 0 deaths)
Pos 2. player 100 / 1 Point   (3 Kills - 2 deaths)
Pos 3. player 200 / -3 Points (1 Kills - 4 deaths)

我想在一个 SQL 查询上执行此操作,但我被卡住了...任何提示都将不胜感激。

您可以使用 union all 和聚合:

select player_id, sum(cnt) score
from (
    select killer_id player_id, 1 cnt from mytable
    union all select death_id, -1 from mytable
) t
group by player_id
order by score desc

如果你还想要玩家排名,你可以使用window函数(这需要MySQL 8.0):

select rank() over(order by sum(cnt) desc) pos, player_id, sum(cnt) score
from (
    select killer_id player_id, 1 cnt from mytable
    union all select death_id, -1 from mytable
) t
group by player_id
order by score desc

您可以使用 union all 和聚合:

select player_id, sum(points)
from ((select killer_id as player_id, 1 as points
       from t
      ) union all
      (select death_id, -1 as points
       from t
      ) 
     ) kd
group by player_id
order by sum(points) desc;