SQL Compact Edition LEFT OUTER JOIN平均值

时间:2013-01-23 23:39:46

标签: sql join sql-server-ce left-join outer-join

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

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

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

我试图实现它返回一行,显示产品的名称及其平均评级。似乎无法弄清楚如何。

提前致谢。

1 个答案:

答案 0 :(得分:2)

您想查看the GROUP BY statement。例如:

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语句时,您可能希望根据一个或多个聚合函数的结果过滤结果集。您使用the HAVING statement执行此操作:

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;