Add up conditional counts on multiple columns of the same table

后端 未结 4 1210
清歌不尽
清歌不尽 2021-01-21 01:16

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

4条回答
  •  逝去的感伤
    2021-01-21 01:49

    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
    

提交回复
热议问题