如何根据SQL中的每个不同ID对数字进行平均?

sih*_*hao -4 sql sql-server sql-server-2008

我有CommentRating一个持有外键的表DrinkId.我试图获得每个的平均评分DrinkId,并且我想要显示评分最高的前三名饮料.

commentRating  drinkID 

     9           7

     9           4

     8          11

     8           7

     7           4

     6           4

     6          11
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止的SQL,但我不知道如何更改它.

Select TOP(3)(AVG(commentRating)),DISTINCT(drinkID)
FROM  Comment order by commentRating desc
Run Code Online (Sandbox Code Playgroud)

我如何平均评分,选择前三个评级的饮料,并在SQL中返回?

Mat*_*eid 5

你需要得到GROUP BY的结果是drinkID:

SELECT TOP 3 AVG(commentRating), drinkID
FROM Comment
GROUP BY drinkID
ORDER BY AVG(commentRating) DESC
Run Code Online (Sandbox Code Playgroud)

我建议您阅读有关详细信息的最喜欢的SQL文档GROUP BY.对于T-SQL,它是MSDN上的GROUP BY(Transact-SQL).

AVG是一个聚合函数.同样,我建议你阅读有关聚合函数的一些文档,在T-SQL中也可以在MSDN库中阅读.