如何列出在任何一年中发行的每一部电影中扮演过角色的电影演员

时间:2015-10-12 19:43:12

标签: sql postgresql

我有两个数据库:一个是使用列actor_name和movie_title的表actions_gigs,另一个是包含movie_title和release_year列的表电影。我想创建一个SQL查询,列出在给定的release_year中参与每一部电影的所有演员的名字,并显示两列:演员的名字(actor_names)以及他们参与每部电影的年份(RELEASE_YEAR)。

例如:

True

这意味着我想要返回的表是

          movie_title          | release_year
    ------------------------------------------
    'The Green Mile'           | 2000
    'Titanic'                  | 1997
    'Cast Aways'               | 2000
    'Independence Day'         | 1997

          actor_name           | movie_title
    -------------------------------------------------
    'Leonardo DiCaprio'        | 'Titanic'
    'Tom Hanks'                | 'The Green Mile'
    'Will Smith'               | 'Independence Day'
    'Tom Hanks'                | 'Cast Aways'

我一直在尝试使用子查询和外连接,但我还没有完全找到解决方案。我知道我必须使用计数,但我不确定如何以这种方式多次应用它。

3 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

select m.release_year
     , a.actor_name
     , count(1) total_movies
from movies m
    join actors a on a.movie_title = m.movie_title
group by m.release_year, a.actor_name
order by m.release_year, a.actor_name -- or however you want to order it

答案 1 :(得分:0)

这是一种方式:

SELECT y.actor_name, y.release_year
FROM (SELECT release_year, COUNT(*) AS cnt
      FROM movies
      GROUP BY release_year) AS x
INNER JOIN (SELECT actor_name, release_year, COUNT(*) AS cnt
            FROM acting_gigs AS t1
            INNER JOIN movies AS t2 ON t1.movie_title = t2.movie_title
            GROUP BY actor_name, release_year) AS y
ON x.release_year = y.release_year AND x.cnt = y.cnt

派生表x包含每年的电影数量,而派生表y包含每年/每位演员的电影数量。

JOIN谓词:

  • x.release_year = y.release_year
  • x.cnt = y.cnt

保证,在特定年份,只返回参与当年所有电影的演员。

Demo here

这是使用窗口函数的另一种可能更有效的方式:

SELECT DISTINCT actor_name, release_year
FROM (
SELECT actor_name, release_year,
       COUNT(*) OVER (PARTITION BY actor_name, release_year) AS cntPerActorYear,
       COUNT(*) OVER (PARTITION BY release_year) AS cntPerYear
FROM acting_gigs AS t1
INNER JOIN movies AS t2 ON t1.movie_title = t2.movie_title ) AS t
WHERE cntPerActorYear = cntPerYear

Demo here

答案 2 :(得分:0)

以下是在MS SQL中执行此操作的方法 - http://sqlfiddle.com/#!6/492ac/3

SELECT
  A.ActorName,
  M.ReleaseYear
FROM
  Movies AS M
INNER JOIN
  ActorsMovies AS A
ON
  M.MovieTitle = A.MovieTitle