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:
- challenger_id (user_id fk)
- challengee_id (user_id fk)
- challenger_won (boolean)
As you can see, a user can be a challenger or a challengee, but not both.
- If the user is a challenger and the challenger_won = true, then it is considered a win.
- If the user is a challengee and the challenger_won = false, then it is considered a win.
- If the challenger_won = null, then just disregard it.
How would I write the SQL for this?
What about this?
If
challenger_wonis NULL, both queries in the UNION will ignore the row, as required.If you don’t like UNION ALL, you can use, instead:
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.