I am looking for a \"better\" way to perform a query in which I want to show a single player who he has played previously and the associated win-loss record for each such oppone
Solution with correlated subquery:
SELECT *,
(SELECT COUNT(*) FROM match WHERE loser_id = p.player_id),
(SELECT COUNT(*) FROM match WHERE winner_id = p.player_id)
FROM dbo.player p WHERE player_id <> 1
Solution with UNION
and conditional aggregation:
SELECT t.loser_id ,
SUM(CASE WHEN result = 1 THEN 1 ELSE 0 END) ,
SUM(CASE WHEN result = -1 THEN 1 ELSE 0 END)
FROM ( SELECT * , 1 AS result
FROM match
WHERE winner_id = 1
UNION ALL
SELECT loser_id , winner_id , -1 AS result
FROM match
WHERE loser_id = 1
) t
GROUP BY t.loser_id