我有两张table book(isbn, title, authorID, genre, pubYear, publisher, rrPrice, avgRating)
以及 orderDetails(oNo, bookISBN, quantity)
. 有多个订单有自己的orderdetails,因此每本书可以有多个orderdetails与它们关联并有自己的数量。我需要找到订单最多的书。我已经获得了正确的输出,但是我的解决方案非常混乱,涉及到两次使用同一个子查询,我想知道是否有人可以建议一个更干净的实现?我得出的答案如下:
SELECT title, pubYear, orderSum
FROM
(
SELECT title, pubYear,orderSum
FROM
(
SELECT title, pubYear,SUM(quantity) AS orderSum
FROM book INNER JOIN orderDetails ON bookISBN = isbn
GROUP BY title, pubYear) T
GROUP BY title, pubYear) S
WHERE S.orderSum = (select max(S.orderSum) from (SELECT title,
pubYear,orderSum
FROM
(
SELECT title, pubYear,SUM(quantity) AS orderSum
FROM book INNER JOIN orderDetails ON bookISBN = isbn
GROUP BY title, pubYear) T
GROUP BY title, pubYear) S);
2条答案
按热度按时间9rbhqvlz1#
“最简单”的表单将使用窗口函数——但这些函数仅在MySQL8+中可用。
在旧版本中,您可以将其表述为:
0ve6wy6x2#
我就是这样着手解决这个问题的。
选择b.标题,
b.pubYear
,count(o.bisbn)as numberoforders from books as b inner join orderdetails as o on b.bisbn=o.bisbn group by b.title,b.pubyear order by numberoforders desc