Сначала вы получаете среднее значение Rate
для каждого BookId
с group by
, а затем присоединитесь к Books
, чтобы получить детали каждой книги:
SELECT b.*, g.Rate FROM Books AS b INNER JOIN (
SELECT T1.BookId, AVG(T2.Rate) AS Rate
FROM Books AS T1
INNER JOIN BookRates as T2
ON T1.BookId = T2.BookId
GROUP BY T1.BookId
) AS g on g.BookId = b.BookId
ORDER BY g.Rate desc
Если есть книги, которые не оценены, то вы должны использовать левое соединение:
SELECT b.*, coalesce(g.Rate, 0) AS Rate FROM Books AS b LEFT JOIN (
SELECT T1.BookId, AVG(T2.Rate) AS Rate
FROM Books AS T1
INNER JOIN BookRates as T2
ON T1.BookId = T2.BookId
GROUP BY T1.BookId
) AS g on g.BookId = b.BookId
ORDER BY coalesce(g.Rate, 0) desc