casewhen多条件查询_【三】Sqlzoo 表关联与case when

SQL多表查询学习主要包括下列知识点:

  • 表的加法
  • 表的联结(包括:交叉联结、内联结、左联结、右联结、全联结)
  • case when的表达式

826de0d8863a2905efc865f3728a47cb.png
  • 内联结、左联结、右联结的示意文氏图:

a86c814913625d05f4d685bb65159d50.png

1.show the name of all players who scored a goal against Germany

SELECT 

第一个条件:为了找出对手是德国的比赛的id,

第二个条件:为了找出在对手是德国时候进球的队员

链接表时候条件where是为了筛选出结果进行匹配

2.For every match involving 'POL', show the matchid, date and the number of goals scored.

SELECT matchid,mdate, COUNT(teamid)
FROM game JOIN goal ON matchid = id 
WHERE (team1 = 'POL' OR team2 = 'POL')  
GROUP BY matchid

这里错误地加上了matchid='POL' 导致结果少了 ,这里记分不管是哪个球队得分,都计入,如果多了matchid='POL',就只计POL得分。

3.

f7a846a95c3c12ef2f284ff8d22741fb.png

有两列数据要分组汇总,而不是一列汇总

在sum函数里面用case when 表里列名=组1 THEN result1 ELSE result2 END

4.Obtain the cast list for the film 'Alien'

SELECT actor.name 
FROM actor 
INNER JOIN casting 
ON casting.actorid=actor.id 
INNER JOIN movie 
ON movie.id=casting.movieid -----这里直接联结上已经联好的表
WHERE title='Alien'----最后筛选

5.List the film title and the leading actor for all of the films 'Julie Andrews' played in.

SELECT title, name FROM movie
JOIN casting ON movie.id=casting.movieid
JOIN actor on actor.id=casting.actorid
WHERE casting.movieid IN (                    ------()里为julie参演的电影
SELECT movie.id from movie
JOIN casting ON movie.id=casting.movieid
JOIN actor ON actor.id=casting.actorid
WHERE actor.name='Julie Andrews') AND ord=1

6.Obtain a list, in alphabetical order, of actors who've had at least 15 starring roles.

SELECT name
FROM actor
WHERE id IN  (SELECT actorid
               FROM casting
               WHERE ord=1
               GROUP BY actorid
               HAVING COUNT(actorid)>=15)
ORDER BY name

HAVING +count 的用法

HAVING +聚合函数 count avg sum

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值