任务:按字母顺序获取至少拥有30个主演角色的演员列表。
我的代码:
select name, count(ord=1)
from casting
join actor on actorid=actor.id
where ord=1 and count(ord=1) and exists ( select 1 from casting
where count(movieid)>=30)
group by actorid,name
order by name
这给我一个错误-无效使用按功能分组。
答案 0 :(得分:2)
加入表,按参与者分组,然后将条件放入Haveing子句中。
$ rm $(find . -path './src/**' -name __tests__ | sed -E 's/([^ ]+__tests__)/\1\/*.js \1\/*.js.map/g' | xargs echo rm
rm: cannot remove './src/game/__tests__/*.js': No such file or directory
rm: cannot remove './src/game/__tests__/*.js.map': No such file or directory
rm: cannot remove './src/helpers/__tests__/*.js': No such file or directory
rm: cannot remove './src/helpers/__tests__/*.js.map': No such file or directory
表达式select
a.name,
sum(case c.ord when 1 then 1 else 0 end) starringroles
from actor a inner join casting c
on c.actorid = a.id
group by a.id, a.name
having sum(case c.ord when 1 then 1 else 0 end) >= 30
order by a.name
将计算出主演角色的数量(带有sum(case c.ord when 1 then 1 else 0 end)
)。
答案 1 :(得分:1)
您不能在where
上使用聚合,而需要having
select name, count(*)
from casting
join actor on actorid=actor.id
where ord=1
and exists ( select 1 from casting
having count(movieid)>=30)
group by actorid,name
having count(movieid)>=30
order by name
答案 2 :(得分:0)
select MAX(name) AS name, count(*) AS roles
from casting
join actor on actorid=actor.id
group by actorid
HAVING COUNT(*)>=30
order by name;
答案 3 :(得分:0)
这是SQLZoo中问题#13中的一个问题。下图说明了表格:
有关数据库的一些描述:
该数据库具有多对多关系的两个实体(电影和演员)。每个实体都有自己的表。第三个表Cast用来链接它们。这种关系是多对多的,因为每部电影都有许多演员,而且每个演员都出现在许多电影中。
这是我发现有效的答案:
select A.name
from actor A
inner join casting C
on C.actorid = A.id
where C.ord =1 /*only the lead roles*/
group by A.id /*grouped by Actor ID*/
having count(C.movieid) >=15 /*at least 15 starring roles*/
order by A.name /* in alphabetical order*/