Postgresql - 获取列中具有最大值的行

Postgresql - Getting row with max value in column

我想形成一个 sql 查询,其中 returns 一些行数据,在某些组中具有最大值。考虑以下示例进行演示:

共有三个表:国家、出版商和图书。每个出版商都属于一个国家,每本书都有一个出版商。定义可能看起来像

Country(country_id, country_name)
Publisher(pub_id, pub_name, fk_pub_country)
Book(book_id, book_name, release_date, fk_book_publisher)

我想 select (country_id, book_name) 按国家/地区分组,这样每一行都包含该国家/地区最近发行的图书的名称。如果同一天发布多本书,我应该拿id最高的那本。

如果我只使用group by -clause和max,我不能包括书名。如果我 select 查看 (country_id, max_date) 并将其与出版商和书籍结合起来,我可能会收到每个国家/地区的多行。我怎样才能达到预期的效果?

您可以使用子查询:

select c.country_id,
       (select b.book_name 
        from Book b 
             join Publisher p on p.pub_id = b.fk_book_publisher 
        where p.fk_pub_country = c.country_id 
        order by b.release_date desc, b.book_id desc limit 1) as book_name
from Country c
SELECT DISTINCT ON (country_id)
  country_id,
  book_name
FROM country
JOIN publisher ON fk_pub_country = country_id
JOIN book ON fk_book_publisher = pub_id
ORDER BY
  country_id,
  release_date DESC,
  book_id DESC

你说:

If I just use group by -clause and max, I cannot include the book name.

但是你不能让 Postgres 那样指挥你。只需从结果数组中获取 n 排序记录中的第一个(未经测试):

SELECT
  country_id,
  (array_agg(book_name))[1] as book_name
FROM country
JOIN publisher ON fk_pub_country = country_id
JOIN book ON fk_book_publisher = pub_id
GROUP BY country_id ORDER BY release_date DESC;

因为它们是按您的要求排序的,所以 (array_agg(...))[1] 从列表中取出第一项,嘿,你有一份炖菜。