在SQL中具有多个条件的Count()

时间:2013-05-08 19:18:00

标签: sql

我试图看看一名球员在他最喜欢的任何一个球场丢了一场比赛的次数。我尝试了以下内容,但它没有返回正确的值:

select players.name,
count (case when players.team <> matches.winner and favstadiums.stadium = matches.stadium then 1 else null end) as LOSSES
from players
join favstadiums
on favstadiums.player = players.name 
join matches
on favstadiums.stadium = matches.stadium
group by players.name;

我也尝试过左/右连接,但输出没有区别。

以下是数据库的关系图供参考:

enter image description here

有什么想法吗?

4 个答案:

答案 0 :(得分:2)

您的join条件没有让球员在球场上比赛。您需要添加球员队伍在最喜欢的体育场中所扮演的条件:

select players.name,
       SUM(case when players.team <> matches.winner then 1 else 0 end) as Losses
from players join
     favstadiums
     on favstadiums.player = players.name join
     matches
     on favstadiums.stadium = matches.stadium and
        players.team in (matches.home, matches.away)
group by players.name;

答案 1 :(得分:1)

尝试以下方法:

SELECT  P.name,
        COUNT(DISTINCT M.ID) AS Losses
FROM Player P
INNER JOIN favStadiums FS
    ON P.name = FS.player
INNER JOIN Match M
    ON (P.team = M.home OR P.team = M.away)
WHERE FS.stadium = M.stadium
AND M.winner <> P.team

答案 2 :(得分:0)

这应该有效,请查看

select player.name,
count(match.id) as LOSSES
from player
inner join team
    on player.team = team.name 
left join match
    inner join favStadiums on favstadiums.stadium = matches.stadium and favStadiums.player = player.name
    on (match.home = team.name or match.away = team.name) and match.winner <> team.name     
group by players.name;

答案 3 :(得分:0)

又是另一个混​​合...我缩进我的联接,以显示我如何得到细节的关系。

SELECT
      P.`Name`,
      SUM( case when P.team <> M.winner then 1 else 0 end ) as FavStadiumLosses
   from
      Player P
         Join Match M
            ON P.Team = M.`Home`
            OR P.Team = M.Away
            Join Stadium S
               ON M.Stadium = S.Stadium
               JOIN FavStadiums FS
                  ON P.`Name` = FS.Player
                  AND M.Stadium = FS.Stadium
   group by
      P.`Name`