首页 > 解决方案 > 无法使用按功能分组解决问题

问题描述

任务:按字母顺序获取至少担任过 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

它给了我错误,-按功能分组无效。

标签: sqlgroup-by

解决方案


加入表格,按参与者分组并将条件放在有子句中。

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)将计算主演角色的数量(带有ord = 1)。


推荐阅读