我使用下面的查询显示所有比赛的得分摘要表。 桌面游戏有id,mdate,stadium,team1,team2。 表格目标有matchid,玩家名称,teamid,gtime,因此它记录每一个目标。
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 JOIN goal ON matchid = id
GROUP BY mdate, team1, team2
ORDER BY mdate, matchid, team1, team2
我的查询重新丢失了2个案例,其中两个团队得分为0。
请帮助告知我的语法是否合适。
答案 0 :(得分:3)
如果特定LEFT JOIN
的{{1}}表格中没有行,您应该使用goal
,但仍希望game
行生成结果行:
game
当没有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
要计数时,这会产生NULL
而不是0
s,但可以通过用{包裹goal
表达式来解决这个问题。 {1}},如果结果为SUM
非常重要。