我需要返回最常购买的书的书名。如果购买了多本相同金额的书,则会收到错误消息:
SELECT title
FROM books JOIN orderitems
USING (isbn) WHERE isbn=
(SELECT isbn
FROM orderitems
HAVING SUM (quantity) =
(SELECT MAX(SUM(quantity))
FROM orderitems
GROUP BY isbn)
GROUP BY isbn)
GROUP BY title;
答案 0 :(得分:1)
您的子查询返回不支持=运算符的多行,因此我使用了in
SELECT title
FROM books JOIN orderitems
USING (isbn) WHERE isbn in
(SELECT isbn
FROM orderitems
group by isbn
HAVING SUM (quantity) =
(SELECT MAX(SUM(quantity))
FROM orderitems
GROUP BY isbn
)
)
答案 1 :(得分:0)
使用窗口功能!
SELECT title
FROM (SELECT isbn, title, SUM(quantity) as quantity,
RANK() OVER (ORDER BY SUM(quantity) DESC) as seqnum
FROM books b JOIN
orderitems oi
USING (isbn)
GROUP BY isbn, title
) t
WHERE seqnum = 1;
答案 2 :(得分:0)
您要按订单数量对书籍进行排名,并且仅显示排名最高的书籍(数量最大的书籍排在第一位)。有窗口功能RANK
用于对行进行排名。
您只想选择书名,因此从书中选择书名,并在WHERE
子句中应用您的条件。
select title
from books
where (isbn, 1) in -- ISBN ranked #1
(
select isbn, rank() over (order by sum(quantity) desc)
from orderitems
group by isbn
);