查询返回与电影租赁数据库中观看次数最多的导演配对的用户

时间:2017-12-15 06:25:34

标签: sql oracle

假设一个DB有两个表格,如下所示:

电影(Movie_ID,导演)

租借(CustomerID,Movie_ID)

我需要返回与导演名称配对的用户,他们租借的电影最多。我已经想出如何在MySQL中做到这一点,但无法找到正确的语法来让它在Oracle中运行。

使用MySQL:

SELECT x.CustomerID, x.Director
  FROM (SELECT r.CustomerID, m.Director, COUNT(*) AS DirectorCount
          FROM Rentals AS r
          JOIN Movies AS m
            ON r.Movie_ID = m.Movie_ID
         GROUP BY r.CustomerID, m.Director
       ) x
  JOIN (SELECT x.CustomerID, MAX(x.DirectorCount) AS MaxDirectorCount
          FROM (SELECT r.CustomerID, m.Director, COUNT(*) AS DirectorCount
                  FROM Rentals AS r
                  JOIN Movies AS m
                    ON r.Movie_ID = m.Movie_ID
                 GROUP BY r.CustomerID, m.Director
               ) x
         GROUP BY x.CustomerID
       ) y
    ON x.CustomerID = y.CustomerID AND x.DirectorCount = y.MaxDirectorCount

非功能性Oracle:

WITH x AS (
    SELECT r.CustomerID, m.Director, COUNT(*) AS DirectorCount
          FROM Rentals AS r
          JOIN Movies AS m
            ON r.Movie_ID = m.Movie_ID
         GROUP BY r.CustomerID, m.Director
       )
WITH y AS (
                SELECT x.CustomerID, MAX(x.DirectorCount) AS MaxDirectorCount
          FROM (SELECT r.CustomerID, m.Director, COUNT(*) AS DirectorCount
                  FROM Rentals AS r
                  JOIN Movies AS m
                    ON r.Movie_ID = m.Movie_ID
                 GROUP BY r.CustomerID, m.Director
               )
         GROUP BY x.CustomerID
      ) 
SELECT x.CustomerID, x.Director
JOIN
ON x.CustomerID = y.CustomerID AND x.DirectorCount = y.MaxDirectorCount

2 个答案:

答案 0 :(得分:1)

Oracle中的表别名是在没有AS的情况下指定的。

SELECT x.CustomerID, x.Director
  FROM (SELECT r.CustomerID, m.Director, COUNT(*) AS DirectorCount
          FROM Rentals r
          JOIN Movies  m
            ON r.Movie_ID = m.Movie_ID
         GROUP BY r.CustomerID, m.Director
       ) x
  JOIN (SELECT x.CustomerID, MAX(x.DirectorCount) AS MaxDirectorCount
          FROM (SELECT r.CustomerID, m.Director, COUNT(*) AS DirectorCount
                  FROM Rentals r
                  JOIN Movies m
                    ON r.Movie_ID = m.Movie_ID
                 GROUP BY r.CustomerID, m.Director
               ) x
         GROUP BY x.CustomerID
       ) y
    ON x.CustomerID = y.CustomerID AND x.DirectorCount = y.MaxDirectorCount

答案 1 :(得分:1)

您可以使用窗口函数计算每个客户的最大数量,然后按此过滤来简化此操作。

SELECT
       CustomerID
     , Director
     , directorcount
FROM (
    SELECT
          r.CustomerID
        , m.Director
        , COUNT(*) AS directorcount
        , max(COUNT(*)) over(partition by CustomerID) max_count
    FROM Rentals r
    JOIN Movies m ON r.Movie_ID = m.Movie_ID
    GROUP BY
          r.CustomerID
        , m.Director
    ) d
WHERE directorcount = max_count
  • 在声明表别名时,已经提到过Oracle查询因“AS”而失败。