Q:

SQL Compact Edition LEFT OUTER JOIN Average

I have a table with products and a table with ratings. I have the following query;
SELECT products.name, ratings.rating 
FROM   products 
       LEFT OUTER JOIN ratings 
       ON products.id = ratings.product_id;

Returning me a nice list of rows with the name of the product and every rating separately.
I am trying to achieve that it returns one row showing me the name of the product with its average rating. Can't seem to find out how though.
Thanks in advance.

A:

You want to look into the GROUP BY statement. Example:
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;

Whilst using the GROUP BY statement, you may wish to filter your resultset on the outcome of one or more of your aggregate functions. You use the HAVING statement to do so:
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;

