2

我有 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
4

2 回答 2

3

使用窗口函数。请参阅PostgreSQL 文档中的窗口函数教程

您正在寻找以下方面的内容:

SELECT
  rank() OVER (PARTITION BY publisher ORDER BY sum_of_sold DESC) AS pos
-- ... FROM clause etc here ...
WHERE pos = 1;
于 2013-03-06T19:07:01.620 回答
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
于 2013-03-06T19:22:32.110 回答