SQL从计数中选择最多 - ALL运算符

时间:2013-10-13 11:47:57

标签: sql oracle

我必须遵循架构

Movie(mvID, title, rating, year)
Director(directorID, firstname, lastname)
Genre(mvID*, genre)
Direct(mvID*, directorID*)

我需要知道指导喜剧类型的大多数电影的导演,并根据他们在该类型中制作的电影数量输出他们的详细信息。

所以我有

SELECT Director.DirectorID, Director.FirstName, Director.LastName, COUNT(*)
FROM Direct, Genre, Director
WHERE Direct.mvID = Genre.mvID
AND Genre.genre = 'Comedy'
AND Direct.DirectorID = Director.DirectorID
AND COUNT(*) > ALL
GROUP BY Director.DirectorID, Director.FirstName, Director.LastName

但是我得到了一个不允许出错的群组功能。

2 个答案:

答案 0 :(得分:1)

首先,按导演和流派计算:

SELECT directorID, genre, COUNT(*) num_movies
FROM Movie JOIN Genre
ON Movie.mvID = Genre.mvID
JOIN Direct
ON Movie.mvID = Direct.mvID
GROUP BY directorID, genre

现在,按流派对导演进行排名:

SELECT
   directorID, genre,
   DENSE_RANK() OVER(PARTITION BY genre order by num_movies desc) rank
FROM
(SELECT directorID, genre, COUNT(*) num_movies
FROM Movie JOIN Genre
ON Movie.mvID = Genre.mvID
JOIN Direct
ON Movie.mvID = Direct.mvID
GROUP BY directorID, genre) X

现在,按流派获得最佳导演:

SELECT directorID, genre
FROM (SELECT
   directorID, genre,
   DENSE_RANK() OVER(PARTITION BY genre order by num_movies desc) rank
   FROM
      (SELECT directorID, genre, COUNT(*) num_movies
       FROM Movie JOIN Genre
       ON Movie.mvID = Genre.mvID
       JOIN Direct
       ON Movie.mvID = Direct.mvID
       GROUP BY directorID, genre) )
WHERE rank=1

有一种使用KEEP和FIRST的替代方法,但我个人觉得KEEP ...... FIRST / LAST语法太混乱了。

答案 1 :(得分:0)

这为您提供了一个顶级列表:

select * from (
SELECT Director.DirectorID, Director.FirstName, Director.LastName, COUNT(*)
FROM Direct, Genre, Director
WHERE Direct.mvID = Genre.mvID
AND Genre.genre = 'Comedy'
AND Direct.DirectorID = Director.DirectorID
GROUP BY Director.DirectorID, Director.FirstName, Director.LastName
ORDER BY COUNT(*) desc
) where rownum<2

(如果这是您想要列出的内容。)