Aggregate columns with additional (distinct) filters

后端 未结 3 913
一个人的身影
一个人的身影 2020-11-22 10:32

This code works as expected, but I it\'s long and creepy.

select p.name, p.played, w.won, l.lost from

(select users.name, count(games.name) as played
from u         


        
3条回答
  •  爱一瞬间的悲伤
    2020-11-22 11:24

    select users.name, 
           count(case when games.winner_id > 0 
                      then games.name 
                      else null end) as played,
           count(case when games.winner_id = users.id 
                      then games.name 
                      else null end) as won,
           count(case when games.winner_id != users.id 
                      then games.name 
                      else null end) as lost
    from users inner join games 
         on games.player_1_id = users.id or games.player_2_id = users.id
    group by users.name;
    

提交回复
热议问题