The goal of this SQL query is to return the user with the most fight wins AND a count of the wins.
I have two tables: users and fights.
User has many fights Fight belongs to user
Fight has the following columns of concern:
As you can see, a user can be a challenger or a challengee, but not both.
How would I write the SQL for this?
What about this?
SELECT a.fighter, COUNT(*) AS wins
FROM (SELECT challenger_id AS fighter
FROM fights
WHERE challenger_won = TRUE
UNION ALL
SELECT challengee_id AS fighter
FROM fights
WHERE challenger_won = FALSE
) AS a
GROUP BY a.fighter;
If challenger_won
is NULL, both queries in the UNION will ignore the row, as required.
If you don't like UNION ALL, you can use, instead:
SELECT a.fighter, SUM(a.wins) AS wins
FROM (SELECT challenger_id AS fighter, 'R' AS role, COUNT(*) AS wins
FROM fights
WHERE challenger_won = TRUE
GROUP BY fighter, role
UNION
SELECT challengee_id AS fighter, 'E' AS role, COUNT(*) AS wins
FROM fights
WHERE challenger_won = FALSE
GROUP BY fighter, role
) AS a
GROUP BY a.fighter;
The first part of the UNION generates rows with 'R' as role (for 'challengeR won') and the fighter ID and a count of the fights won. The second part generates rows with 'E' as role (for 'challengeE won') and the fighter ID and a count of the fights won. The role is necessary in case some fighter won 3 fights as challenger and 3 fights as challengee; without the role, the two entries with the same fighter and count would be collapsed into one. You then sum the wins for each fighter in each role.
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.