可以在sql中平均和统计一起工作吗?

时间:2013-12-04 10:06:53

标签: sql oracle

我的数据库中有两个表,它们看起来像这样

create table restaurants(
restID number(8) NOT NULL,(PK)
name varchar(50),
photo varchar(50))

create table review_Restaurants(
commentID number(8) NOT NULL,
reviewDate timestamp,
commentValue varchar(100),
rating number(1),
userName varchar (25) not null,
restID number(8) not null,);

我想做的是从数据库中获取最好的餐厅(更高的评分和评论)图像并在屏幕上显示。

我解决这个问题的方法是,我会计算每次休息时的平均评分,这个评分将大于3,以及评论超过5的人。

select ((avg)rating > 3) as "rating",(count(reviews) > 5) as "review"
from review_restaurant
group by restID;

但它不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:3)

SELECT restID
     , Avg(rating) As "rating"
     , Count(reviews) As "review"
FROM   review_restaurant
GROUP
    BY restID
HAVING Avg(rating) > 3
AND    Count(reviews) > 5

如果你将HAVING条款从上述声明中删除,它将返回所有餐厅评论及其平均评分和评论数量。

HAVING子句与WHERE子句非常相似,但细微差别在于HAVING子句在聚合发生之后应用

另一种替代方法是使用子查询

SELECT restID
     , rating
     , review
FROM   (
        SELECT restID
             , Avg(rating) As "rating"
             , Count(reviews) As "review"
        FROM   review_restaurant
        GROUP
            BY restID
       ) As a_subquery
WHERE  rating > 3
AND    reviews > 5

与使用HAVING条款相同的逻辑也适用于此...我们计算所有平均评分和评论数量,然后我们应用我们的标准。


如果要从restaurants表中检索相应的信息,那么一旦我们需要在子查询上方进行查询并将其连接回restaurants表。

SELECT restaurants.restID
     , restaurants.name
     , restaurants.photo
     , top_restaurants.rating As average_rating
     , top_restaurants.review As number_of_reviews
FROM   restaurants
 INNER
  JOIN (
        SELECT restID
             , Avg(rating) As "rating"
             , Count(reviews) As "review"
        FROM   review_restaurant
        GROUP
            BY restID
        HAVING Avg(rating) > 3
        AND    Count(reviews) > 5
       ) As top_restaurants
    ON top_restaurants.restID = restaurants.restID