我正在尝试使用嵌套在游标for循环内的for循环在PLSQL中执行趋势分析。我们的目标是让在2000年至2013年之间,在5年内至少演过8部电影的演员返回。
例如,期望的输出将是:Wahlberg,Mark在2009年至2013年间播放了10部电影。 这是我收到的错误:
这是到目前为止我正在使用的代码:
DECLARE
t movie.yr%TYPE;
actor_id actor.id%TYPE;
total INTEGER;
name actor.name%TYPE;
CURSOR c_actor IS
select *
from (select actor.name AS name, count(movie.title) AS total
from actor, movie, casting
where movie.id = casting.movie_id
and actor.id = casting.actor_id
and movie.yr >= 2000 and movie.yr <=2013
group by actor.name
order by count(movie.title) DESC)
where rownum <= 10;
BEGIN
for v_actor in c_actor
LOOP
for t in 2000 .. 2009
LOOP
select name, total
into name, total
from actor, movie
where movie.yr between t and t+4
and actor_id = v_actor.actor_id
and total >= 8
group by name;
dbms_output.put_line(name||' played in '||total||' movies between '||t||' and '||t+4);
END LOOP;
END LOOP;
END;
答案 0 :(得分:2)
看来您过于复杂了。这应该起作用:
begin
for v_actor in (select a.name, count(*) total
from actor a join casting c on a.id = c.actor_id
join movie m on m.id = c.movie_id
where m.yr between 2000 and 2013
group by a.name
having count(*) >= 8
)
loop
dbms_output.put_line(v_actor.name ||' acted ' || v_actor.total ||' times');
end loop;
end;
我认为您在几个小时前提出了一个问题(并将其删除),犯了同样的错误。例如:您创建了一个名为total
的变量,并-同时将其放在游标的select
语句中。您希望显示由游标获取的值,而不是变量本身,除非游标读取到该变量中-但这是在您从游标显式打开/获取而不是在游标FOR
循环中完成的。使用它,您可以使用游标变量并使用它来显示这些值。
答案 1 :(得分:1)
您在光标查询中没有得到actor_id
。
select *
from
(
select a.name AS name, count(m.title) AS total
from actor a
join casting c
on a.id = c.actor_id
join movie m
on m.id = c.movie_id
where m.yr >= 2000
and m.yr <=2013
group by actor.name
order by count(movie.title) desc
)
where rownum <= 10;