2017-01-21 30 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!