To calculate wins and losses of each user without having to join the table to itself and use OUTER joins, it is possible to just select wins and losses separately and do a UNION ALL between them, but with additional information if given row represents a win for the user, or a loss.
Then, it's easy to calculate all wins and losses for each user. The tricky part was to incorporate the option for specifying to which user you would like to compare the profiles. I did that with a variable which is set to the value of percentage
of the user with given user_id
, which you can change from a constant to a variable.
Here is my proposal (comparing to user with id = 6):
SELECT
player_id AS id_user,
wins,
losses,
wins + losses AS total,
wins / (wins + losses) AS percent
FROM (
SELECT
player_id,
SUM(is_a_win) wins,
SUM(is_a_loss) losses,
CASE
WHEN player_id = 6
THEN @the_user_score := SUM(is_a_win) / (SUM(is_a_win) + SUM(is_a_loss))
ELSE NULL
END
FROM (
SELECT id_user_winner AS player_id, 1 AS is_a_win, 0 AS is_a_loss FROM user_versus
UNION ALL SELECT id_user_loser, 0, 1 FROM user_versus
) games
GROUP BY player_id
) data
WHERE
ABS(wins / (wins + losses) - @the_user_score) <= 0.1
;
Output:
ID_USER WINS LOSSES TOTAL PERCENT 6 8 2 10 0.8 9 6 1 7 0.8571
You could of course remove the user whose profile is the base for comparison by adding player_id != 6
(or, in the final solution, some variable name) condition to the outermost WHERE
clause.
Example at SQLFiddle: Matching Profiles - Example
Could you provide some feedback if this is what you were looking for, and, if not, what output would you expect?