多个表上的SQL查询,AVG和COUNT

时间:2014-04-28 23:49:27

标签: mysql sql sql-server

我需要一个查询,我使用的查询因某种原因无法正常运行

以下是查询中涉及的所有表格。

sql tables for the query

以下是我想要的查询: 显示包含平均评分和推荐数量的图书清单

结果应该是这样的: result of query

我已尝试过的内容:

SELECT        book.isbn, AVG(ratings.rating) AS [AVG Ratings], COUNT(recommend.isbn) AS [Number of recommendation]
FROM            book INNER JOIN
                         recommend ON book.isbn = recommend.isbn INNER JOIN
                         ratings ON book.isbn = ratings.isbn
GROUP BY book.isbn

但它不起作用,不知何故,AVG评级效果很好,但建议数没有,它与评级表冲突。

这是结果:

enter image description here

然而,当我单独尝试每一个时,一切都很有效:

对于AVG评级:

SELECT        book.isbn, AVG(ratings.rating) AS [AVG Ratings]
FROM            book INNER JOIN
                         ratings ON book.isbn = ratings.isbn
GROUP BY book.isbn

结果如下:

enter image description here

对于推荐#:

SELECT        book.isbn, COUNT(recommend.isbn) AS [Number of recommendation]
FROM            book INNER JOIN
                         recommend ON book.isbn = recommend.isbn
GROUP BY book.isbn

结果如下:

enter image description here

所以我想要一个查询将两个视图合并为一个视图

4 个答案:

答案 0 :(得分:2)

如果您想获得准确的结果,那么您需要在加入之前进行聚合:

SELECT b.isbn, r.AvgRating, re.NumRecommendation
FROM  book b LEFT JOIN
      (SELECT r.isbn, AVG(r.rating) as AvgRating
       FROM rating r
       GROUP BY r.isbn
      ) r
      ON b.isbn = r.isbn LEFT JOIN
      (SELECT r.isbn, COUNT(*) as NumRecommendation
       FROM recommendation r
       GROUP BY r.isbn
      ) re
      on b.isbn = r.isbn ;

请注意,我也切换到了左外连接,因此您将获得所有书籍的结果,即使是那些缺少评分或推荐的书籍。

答案 1 :(得分:1)

好吧,你可以将两个视图合并为一个..

在这里,这应该按你想要的方式工作

SELECT l.isbn, v.rating, r.rec
FROM book l, 
    (SELECT isbn, AVG(rating) AS rating FROM ratings GROUP BY isbn) v,
    (SELECT isbn, COUNT(isbn) AS rec FROM recommend GROUP BY isbn) r
WHERE l.isbn=v.isbn AND l.isbn=r.isbn

希望这有帮助。

祝你好运!

答案 2 :(得分:0)

SELECT 
  book.isbn, 
  IFNULL(AVG(ratings.rating),"Not yet rated") AS [AVG Ratings],
  IFNULL(COUNT(DISTINCT recommend.iduse),0) AS [Number of recommendation]
FROM
  book
  LEFT JOIN recommend ON book.isbn = recommend.isbn 
  LEFT JOIN ratings ON book.isbn = ratings.isbn
GROUP BY book.isbn

应该诀窍:

  • 计算推荐图书的不同用户将解决笛卡尔产品问题
  • 左边加入通常的IFNULL()管道将使其适用于既没有推荐也没有评级的书籍

答案 3 :(得分:0)

如果您使用的是SQL Server,则可以使用over子句:

SELECT 
  B.isbn, 
  AVG(ra.rating) OVER (PARTITION BY B.isbn) AS [AVG RATE],
  COUNT(re.isbn) OVER (PARTITION BY B.isbn) AS [RECOMMEND COUNT]
FROM Book B
LEFT JOIN recommend re ON B.isbn = re.isbn 
LEFT JOIN ratings ra ON B.isbn = ra.isbn