电影评分最高?

时间:2014-01-15 06:00:57

标签: sql sql-server sql-server-2008

找到平均评分最高的电影。返回电影标题和平均评分。

我尝试了这个并且卡住了,因为如果我添加mid我将无法检索mid, max(avg_stars),那么它将会max提供mid,我只需要一个max select max(avg_stars) from ( select top 1 mid, avg(stars) as avg_stars from rating group by mid order by avg_stars desc ) z 值。

http://sqlfiddle.com/#!3/e3ee1/13

Snow White 4.5

例外输出{{1}}以及如果两部电影具有相同的最大值(avg_stars),我该如何处理。

4 个答案:

答案 0 :(得分:2)

这将完美地满足您的目的。有表现 -

SELECT
    Title
    ,AVG_RATING
FROM
(
    SELECT
        M.Title
        ,M.mID
        ,CAST(ROUND(AVG(R.stars),2) AS DECIMAL(10,2)) AS AVG_RATING
        ,RANK() OVER (ORDER BY AVG(R.stars) DESC) RATING_RANK
    FROM Movie M
    INNER JOIN Rating R
        ON M.mID = R.mID
    GROUP BY M.Title,M.mID
)RANKED_RATING
WHERE RATING_RANK = 1

您可能需要根据您的桌子定义玩一点点。

注意 - 如果2部或更多部电影的平均评分最高 - 所有电影都将排名为1,所有电影都会被选中。如果您仍然只想要一个 - 您需要定义一个关于您想要选择哪个规则的规则。

答案 1 :(得分:1)

试试这个http://sqlfiddle.com/#!3/e3ee1/143

;WITH CTE as
(
select r.mid, avg(r.stars) as avg_stars, m.title
from rating r
 INNER JOIN Movie m ON m.mid=r.mid
group by r.mid, m.title
--order by avg_stars desc
) 
select TOP 1 mid, title,avg_stars from CTE
Group by avg_stars,mid,title
--having avg_stars=Max(avg_stars)
Order By avg_stars desc

输出:

   MID    TITLE         AVG_STARS
   106    Snow White    4.5

答案 2 :(得分:0)

SELECT TOP 1 MAX(m.title) AS title, AVG(stars) AS averageStars
FROM rating r
JOIN movie m
    ON r.mId = m.mId
GROUP BY r.mId
ORDER BY AVG(stars) DESC, 
          --Order by a seond column of your 
          --choice to break ties for AVG(stars)
         MAX(m.title)

答案 3 :(得分:0)

你可以优化或提出更干净的东西,但这有效:

SELECT m.title, AVG(r.stars) AS AverageStars
FROM       Rating AS r (NOLOCK)
INNER JOIN Movie  AS m (NOLOCK) ON m.mID = r.mID
GROUP BY r.mID, m.Title
HAVING AVG(r.stars) =
(
    SELECT TOP 1 AVG(stars) AS AverageStars
    FROM Rating (NOLOCK)
    GROUP BY mID
    ORDER BY AverageStars DESC
)