简体   繁体   中英

How to get ratio between the count of two columns grouped together in mysql (leaderboard kill/death ratio)

I've got a leaderboard in a pvp shooter game where I want to display the top 20 players ordered by their kill / death ratio (total kills divided by their total deaths)

I have a kills table that tracks kills and looks something like:

| killer_id | killed_id | date | 
| patrick   | jim       | 2021-03-01 |
| greyson   | jim       | 2021-03-02|
| jim       | patrick   | 2021-03-03|

I can get the total kills by doing something like:

SELECT COUNT(*) as total_kills 
FROM kills 
GROUP BY killer_id 
ORDER BY total_kills DESC 
LIMIT 20

And I can get the total deaths by doing something like:

SELECT COUNT(*) as total_deaths 
FROM kills 
GROUP BY killed_id 
ORDER BY total_deaths DESC 
LIMIT 20

However, I can't seem to group the query together so that I'm returning a list of the best ratios. It would look like:

| player_id | kill_death_ratio (total kills / total deaths) |
| patrick   | 2.1            |
| jim       | 1.0            |
| greyson   | .9            |

Is this even possible in a single query?

Use this query:

SELECT killer_id player_id FROM kills UNION SELECT killed_id FROM kills

to get all the players in the table.
Then join it with LEFT joins to your queries:

SELECT p.player_id, 
       COALESCE(t1.total_kills, 0) / t2.total_deaths kill_death_ratio
FROM (SELECT killer_id player_id FROM kills UNION SELECT killed_id FROM kills) p
LEFT JOIN (
  SELECT killer_id, COUNT(*) total_kills 
  FROM kills 
  GROUP BY killer_id 
) t1 ON t1.killer_id = p.player_id  LEFT JOIN (
  SELECT killed_id, COUNT(*) total_deaths 
  FROM kills 
  GROUP BY killed_id 
) t2 ON t2.killed_id = p.player_id

Or, without your queries:

SELECT player_id, SUM(killer) / SUM(killed) kill_death_ratio
FROM (
  SELECT killer_id player_id, 1 killer, 0 killed
  FROM kills
  UNION ALL
  SELECT killed_id, 0, 1
  FROM kills
) t
GROUP BY player_id

See the demo .
Results (for your sample data):

player_id kill_death_ratio
jim 0.5
patrick 1.0
greyson null

Notice that you will get null for players that were never killed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM