简体   繁体   中英

Multiple aggregate count columns SQL

I have a table that roughly looks like the following:

winner_name loser_name
Person A Person B
Person A Person C
Person B Person A
Person C Person B

I'm trying to return a table that looks like the following:

player_name number_wins number_losses
Person A 2 1
Person B 1 2
Person C 1 1

I can't quite figure out how to get there. I have been able to write a query that returns player_name and either number_wins or number_losses, but not both.

SELECT winner_name AS player_name, COUNT(*) AS number_wins
FROM my_table
GROUP BY player_name

I have looked into using procedures, functions, and subqueries to do this but I haven't found the right solution yet. Any direction would be helpful.

You need to pivot the names into the same column using UNION . Then you can calculate the sum of wins and losses.

SELECT player_name, SUM(win) AS number_wins, SUM(loss) AS number_losses)
FROM (
    SELECT winner_name AS player_name, 1 AS win, 0 AS loss
    FROM my_table
    UNION ALL
    SELECT loser_name AS player_name, 0 AS win, 1 AS loss
    FROM my_table
) AS x
GROUP BY player_name

Since each aggregate statistic is for a different group (one for winner_name , the other for loser_name ), they can't be calculated in the same query, but each query can be run separately and then combined with a JOIN . Simply take each query:

SELECT winner_name AS player, COUNT(loser_name) AS wins
  FROM games 
  GROUP BY winner_name
;

SELECT loser_name AS player, COUNT(winner) AS losses
  FROM games
  GROUP BY loser_name
;

and join on the common attribute, the player name:

SELECT gw.player, gw.wins, gl.losses
  FROM (
      SELECT winner_name AS player, COUNT(loser_name) AS wins
        FROM games 
        GROUP BY winner_name
      ) AS gw
    JOIN (
      SELECT loser_name AS player, COUNT(winner_name) AS losses
        FROM games
        GROUP BY loser_name
      ) AS gl
      ON gl.player = gw.player
;

Whether using unions or joins, each distinct group that is the basis for aggregate statistics will require a separate sub-select.

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