我有两张桌子:
食谱
RecipeId | UserId |名称|等
和
RecipeRatings
RecipeRatingId | RecipeId | UserId |评级|评论
我想选择食谱列表并包含平均评分。像这样的东西会起作用:
SELECT
Recipes.RecipeId,
Name,
AVG(RecipeRatings.Rating) AS AverageRating
FROM Recipes
INNER JOIN RecipeRatings
ON RecipeRatings.RecipeId = Recipes.RecipeId
GROUP BY Recipes.RecipeId, Recipes.Name
ORDER BY AverageRating DESC
但我真正喜欢的是获得平均值或当前用户评分。似乎我不应该打扰显示平均值,如果用户自己评价更高或更低。
所以给定一个参数@userId,有没有办法选择食谱列表和当前用户评级(如果有),否则RecipeRatings表中的平均值(如果有的话)?
使用AverageRating和MyRating列也可以,并且将由客户端正确显示它。
答案 0 :(得分:1)
你可以试试这个:
SELECT
R.RecipeId,
R.Name,
AVG(RR.Rating) AS AverageRating,
MAX(CASE WHEN RR.UserId = @userId THEN RR.Rating END) AS MyRating
FROM Recipes AS R
LEFT JOIN RecipeRatings AS RR
ON RR.RecipeId = R.RecipeId
GROUP BY R.RecipeId, R.Name
ORDER BY AverageRating DESC
如果您想显示MyRating
,如果它不为空,否则AverageRating
您可以查看COALESCE
功能。
COALESCE(MAX(CASE WHEN RR.UserId = @userId THEN RR.Rating END),
AVG(RR.Rating) AS ActualRating
我还将您的INNER JOIN更改为LEFT JOIN,以便结果中仍然可以显示没有任何评级的食谱。