在sql中使用avg和where时无法查看所有列

3duebb1j  于 2021-07-27  发布在  Java
关注(0)|答案(2)|浏览(371)

图书isbn用户ID用户评分评论日期

1443434973,     2,       2,"Big Brother said this book was a four out of 5.",   2008-06-09
1501142976,     1,       3,"The book was scary, too scary.",                    2006-05-04
1594130000,     3,       4,"The moview was better.",                            2008-06-10
1501142976,     4,       5,"I have been inspired to pursue a career as a clown",2019-03-04

当我询问

SELECT * ,AVG(rating)
FROM geektextdb.rating
WHERE book_isbn = '1501142976';`

我只得到表中的第二行,但我正试图得到第二行和第四行。
p、 我不确定这篇文章是否格式良好,我使用这个网站很多,但任何关于格式的提示将是有益的

qni6mghb

qni6mghb1#

我想你想要的是一个窗口函数,而不是聚合:

SELECT r.*, AVG(rating) OVER (PARTITION BY book_isbn)
FROM geektextdb.rating r
WHERE book_isbn = '1501142976';
mefy6pfw

mefy6pfw2#

这不是有效的聚合查询。如果你想知道 book_isbn ,然后:

select avg(rating) avg_rating
from geektextdb.rating 
where book_isbn = '1501142976'

这将提供一个标量结果集(一行一列),其中包含该书的平均评级。
另一方面,如果您希望所有行以及每行上重复的平均评级,那么您可以使用窗口函数(仅在mysql 8.0中提供):

select r.*, avg(rating) over() avg_rating
from geektextdb.rating r
where book_isbn = '1501142976'

如果您希望同时对所有书籍获得相同的结果,以及对每本书的平均评分,那么下面是等效的查询。
聚合(每本书一行):

select book_isbn, avg(rating) avg_rating
from geektextdb.rating 
group by book_isbn

开窗:

select r.*, avg(rating) over(partition by book_isbn) avg_rating
from geektextdb.rating r

相关问题