0

I'm trying to learn PostgreSQL with the IMDB database and I can't seem to figure out how to include the names of the movie with the largest cast.

I have three tables to work with

  1. Table movie with mov_id, mov_title, mov_year
  2. Table actor with act_id, act_name
  3. Table movie_cast with act_id, mov_id, role

I tried the code below to print out the MAX of the Count which works as expected.

select max(cast_number) from (
    select m.mov_id as movie_id, m.mov_title as movie_title, count(*) as cast_number
    from movie_cast
    join movie m using (mov_id)
    group by m.mov_id, m.mov_title
) As innerTable;

When I try to include the movie_id, and movie_title into the result, it asks me to include those fields in a GROUP BY clause or in an aggregate function. I tried including the fields into the GROUP BY clause:

select innerTable.movie_id, innerTable.movie_title, max(cast_number) from (
    select m.mov_id as movie_id, m.mov_title as movie_title, count(*) as cast_number
    from movie_cast
    join movie m using (mov_id)
    group by m.mov_id, m.mov_title
) As innerTable
group by innerTable.movie_id, innerTable.movie_title;

But this here, gives me all the records, just like what the innerTable gave me. I could have used ORDER BY and LIMIT 1, but I also want to include the names if more than one movie has the max value.

Can someone point me to the right direction on how to achieve the functionality to find the film(s) with the largest cast?

4

1 回答 1

0

使用RANK

with cte as (
    select m.mov_id as movie_id, m.mov_title as movie_title, count(*) as cast_number,
           rank() over (order by count(*) desc) rnk
    from movie_cast
    inner join movie m using (mov_id)
    group by m.mov_id, m.mov_title
)

select mov_id, mov_title, cast_number
from cte
where rnk = 1;

这将返回具有最高演员人数的电影记录。

于 2020-09-28T10:35:36.570 回答