在Sql中汇总具有不同条件的不同列

时间:2017-01-21 08:27:51

标签: sql conditional-statements

有人可以帮忙吗。 我有一张表

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

问题在于玩家' Rob'可以是player_home,下一行是player_away。

我想从这张桌子中得到的是...... 多少次' Rob'赢了一场比赛? 我怎么查询这个? 我很感激帮助! : - )

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

只需从您的条件“Rob已赢”持有的所有行中选择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;

注意:我假设'Rob'在这里唯一识别一名球员,即没有两名名叫Rob的球员,例如在不同球队比赛; - )

HTH!