我有3张桌子:
publisher (id serial pkey, pub_name text)
book (id serial pkey, id_pub INTEGER NOT NULL REFERENCES publisher (id), book_name TEXT)
rank (id SERIAL PKEY, id_book INTEGER NOT NULL REFERENCES book (id), week DATE, selling INTEGER)
并且只想为每个发布商列出畅销书。我现在所拥有的东西归还所有书籍的销售:
SELECT publisher.pub_name, book.book_name, SUM(rank.selling)
FROM rank, publisher, book
WHERE rank.id_book = book.id AND book.id_pub = publisher.id
GROUP BY publisher.pub_name, book.book_name;
这样返回:
BigPublisher, Book1, 100300
GoodPublisher, BeBook, 10003
BigPublisher, Book2, 50200
OldPublisher, N-Book, 20009
GoodPublisher, CeBook, 4000
GoodPublisher, DeBook, 3001
我正在寻找那种结果:
BigPublisher, Book1, 100300
GoodPublisher, BeBook, 10003
OldPublisher, N-Book, 20009
答案 0 :(得分:3)
使用窗口功能。请参阅the window functions tutorial in the PostgreSQL documentation。
您正在寻找以下内容:
SELECT
rank() OVER (PARTITION BY publisher ORDER BY sum_of_sold DESC) AS pos
-- ... FROM clause etc here ...
WHERE pos = 1;
答案 1 :(得分:1)
select
distinct on (pub_name),
pub_name,
book_name,
selling
from (
select
publisher.pub_name,
book.book_name,
sum(rank.selling) selling
from
publisher
inner join
book on book.id_pub = publisher.id
inner join
rank on rank.id_book = book.id
group by 1, 2
) s
order by pub_name, s.selling desc