我的CASE语句查询错误了

时间:2014-04-15 11:09:19

标签: mysql sql select group-by case

我试图解决http://www.sqlzoo.net/wiki/The_JOIN_operation

上的#13

"列出每场比赛的每场比赛,如图所示。这将使用" CASE WHEN"在之前的任何练习中都没有解释过。"

这是我的疑问:

SELECT game.mdate, game.team1, 
SUM(CASE WHEN goal.teamid = game.team1 THEN 1 ELSE 0 END) AS score1,
game.team2,
SUM(CASE WHEN goal.teamid = game.team2 THEN 1 ELSE 0 END) AS score2

FROM game INNER JOIN goal ON matchid = id
GROUP BY game.id
ORDER BY mdate,matchid,team1,team2

我得到了结果"行数太少"。我不明白我错了哪一部分。

6 个答案:

答案 0 :(得分:19)

INNER JOIN仅返回有目标的游戏,即goalgame表之间的匹配。

您需要的是LEFT JOIN。您需要第一个表game中的所有行,但它们不需要匹配goal中的所有行,根据我对您的问题所做的0-0评论:

SELECT game.mdate, game.team1, 
SUM(CASE WHEN goal.teamid = game.team1 THEN 1 ELSE 0 END) AS score1,
game.team2,
SUM(CASE WHEN goal.teamid = game.team2 THEN 1 ELSE 0 END) AS score2

FROM game LEFT JOIN goal ON matchid = id
GROUP BY game.id,game.mdate, game.team1, game.team2 
ORDER BY mdate,matchid,team1,team2

这将返回6月27日葡萄牙和西班牙之间的0-0结果,您的初步答案错过了。

答案 1 :(得分:1)

由于现在两个表中都有相同名称的列,因此无需指定当前列的来源。

SELECT mdate, team1, 

SUM(CASE WHEN teamid = team1 THEN 1 ELSE 0 END) AS score1,

TEAM2,

SUM(CASE WHEN teamid = team2 THEN 1 ELSE 0 END) AS score2

FROM game LEFT JOIN goal ON matchid = id

GROUP BY mdate, team1, team2

ORDER BY mdate,matchid,team1,team2

答案 2 :(得分:0)

对于MySQL,@ mjsqu的答案有效,但是for SQL Server以及specify all the columnsGROUP BY所需的其他一些方言。因此,如果你是MySQL的家庭,请记住,在某些方言中,你必须在GROUP BY中更具体(不幸的是......)。在适用于SQL Server的脚本下面:

SELECT    game.mdate 
,         game.team1
,         SUM(CASE WHEN goal.teamid=game.team1 THEN 1 ELSE 0 END) score1 
,         game.team2
,         SUM(CASE WHEN goal.teamid=game.team2 THEN 1 ELSE 0 END) score2
FROM game LEFT JOIN goal 
  ON game.id=goal.matchid
GROUP BY  game.mdate, goal.matchid, game.team1, game.team2

答案 3 :(得分:0)

SELECT game.mdate, game.team1, 
SUM(CASE WHEN goal.teamid = game.team1 THEN 1 ELSE 0 END) score1,
game.team2,
SUM(CASE WHEN goal.teamid = game.team2 THEN 1 ELSE 0 END) score2
FROM game LEFT JOIN goal ON matchid = id
GROUP BY mdate, team1, team2

答案 4 :(得分:0)

我是使用子查询完成的。

这里的唯一技巧是了解我们需要使用左联接而不是内部联接,因为有些比赛得分为0的游戏如果使用内部联接(0-0情况)则无法捕获到我们的查询中

希望下面的查询有帮助!

select t1.mdate,t1.team1,sum(t1.score1),t1.team2,sum(t1.score2) from(
SELECT mdate,
  team1,
  CASE WHEN teamid=team1 THEN 1 ELSE 0 END score1,
  team2,
  CASE WHEN teamid=team2 THEN 1 ELSE 0 END score2
  FROM game JOIN goal ON matchid = id)t1
group by t1.mdate,t1.team1,t1.team2
order by mdate,team1,team2

答案 5 :(得分:-1)

`

SELECT ga.mdate, ga.team1,
SUM(CASE WHEN go.teamid=ga.team1 THEN 1 ELSE 0 END) score1,
ga.team2,
SUM(CASE WHEN go.teamid=ga.team2 THEN 1 ELSE 0 END) score2
FROM game ga LEFT JOIN goal go ON go.matchid = ga.id
GROUP BY ga.mdate, go.matchid, ga.team1, ga.team2

`