2017-02-16 89 views
1

我想組成一個sql查詢,它返回某些行中的某些數據,這些數據在某些組中具有最大值。考慮下面的示例:Postgresql - 在列中獲取最大值的行

有三個表格:國家,出版商和書籍。每個出版商都屬於一個國家,每本圖書都有一個出版商。定義可能看起來像

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

我想選擇由國家分類(COUNTRY_ID,BOOK_NAME),使每一行包含最近出版的新書在該國的名稱。如果在同一天發佈多本書,我應該得到最高ID的書。

如果我只是使用group by-clause和max,我不能包含書名。如果我選擇查看(country_id,max_date)並將其與發佈商和圖書一起加入,那麼我可能會在每個國家/地區收到多行。我怎麼能達到預期的結果?

+0

作業?添加示例表格數據和預期結果,以及格式化文本。同時向我們展示您當前的查詢嘗試 - 並描述發生了什麼問題。 – jarlh

回答

2
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 
+0

謝謝!考慮到性能,這似乎也是一個很好的解決方案。 – eko

0

你可以使用子查詢:

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 
0

你說:

如果我只是-clause和最大使用羣體,我不能包括書 名。

但是你不能讓Postgres像你一樣老大。只需搶到第一的ň排序記錄從結果數組像這樣(未經):

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]從列表中抓住第一項和,哎,你有一個燉湯布'。