0

我有一张带有产品的表格和一张带有评级的表格。我有以下查询;

SELECT products.name, ratings.rating 
FROM   products 
       LEFT OUTER JOIN ratings 
       ON products.id = ratings.product_id;

分别返回给我一个很好的行列表,其中包含产品名称和每个评级。

我试图实现它返回一行,显示产品名称及其平均评分。似乎无法找出如何。

提前致谢。

4

1 回答 1

2

您想查看GROUP BY 语句。例子:

SELECT products.name AS Product_Name, 
       AVG(ratings.rating) AS Average_Rating
FROM   products 
       LEFT OUTER JOIN ratings 
       ON products.id = ratings.product_id
GROUP BY products.name
ORDER BY products.name;

在使用 GROUP BY 语句时,您可能希望根据一个或多个聚合函数的结果过滤结果集。您使用HAVING 语句来执行此操作:

SELECT products.name AS Product_Name, 
       AVG(ratings.rating) AS Average_Rating
FROM   products 
       LEFT OUTER JOIN ratings 
       ON products.id = ratings.product_id
GROUP BY products.name
HAVING AVG(ratings.rating) >= 3
ORDER BY products.name;
于 2013-01-23T23:43:08.713 回答