SQLZOO练习题(4)

SQLZOO练习题(4)

sqlzoo上较难的一些sql查询练习题及其解题思路。

表格结构:
在这里插入图片描述

题目
List every match with the goals scored by each team as shown. This will use “CASE WHEN” which has not been explained in any previous exercises.
在这里插入图片描述
Notice in the query given every goal is listed. If it was a team1 goal then a 1 appears in score1, otherwise there is a 0. You could SUM this column to get a count of the goals scored by team1. Sort your result by mdate, matchid, team1 and team2.

答案

select mdate, 
team1, sum(case when team1=teamid then 1 else 0 end) score1,
team2, sum(case when team2=teamid then 1 else 0 end) score2
from game left join goal on id=matchid
group by mdate, matchid, team1, team2
order by mdate, matchid, team1, team2;

思路

主要涉及case函数,二表联合查询和group by聚合函数。

使用case when函数,当team1=teamid表示team1有进球,返回1,再用sum()函数聚合team1的进球数。team2同理。

容易忽略的点是要使用game left join goal而不是join(即inner join)。因为要考虑到两只球队都没有进球的情况,即0比0。goal表中只记录进球的数据,因此不会记录0比0的比赛数据。使用inner join将会丢失这部分数据。

希望本文对你有所帮助。

猜你喜欢

转载自blog.csdn.net/weixin_44054605/article/details/88816075