2017-01-21 31 views
0

有人可以帮忙。 我有一个表有在Sql中用不同的条件求和不同列

player_home, 
player_away, 
team_home, 
team_away, 
score_home, 
score_away 

player_home always has team_home and score_home. 
player_away always has team_away and score_away 

问题是一排播放器“罗布”可以player_home和下一行他是player_away。

我想摆脱这张桌子是.. '抢'赢了一场比赛有多少次? 我该如何查询? 我很感激帮助! :-)

回答

0

使用union all结合2查询

select sum(case when player_home = 'rob' and score_home > score_away) 
       then 1 
       else 0 
      end) as wins 
from your_table 
union all 
select sum(case when player_away = 'rob' and score_home < score_away) 
       then 1 
       else 0 
      end) 
from your_table 
0

只需选择1从那里您的条件“罗布曾荣获”包含所有行和0为人人,人行,总有sum

select sum(case 
      when player_home = 'Rob' and score_home > score_away or 
        player_away = 'Rob' and score_away > score_home 
       then 1 
      else 0 end) rob_wins 
from scores; 

注:我认为“罗布”唯一标识在这里的球员,即没有两个球员名为罗布,在不同的球队打比方;-)

HTH!