我有一张这样的 table
table_id | series_id | revision_id | year
------------------------------------------
1 | 1 | 1 | 2010
2 | 2 | 1 | 2009
3 | 2 | 2 | 2008
4 | 2 | 2 | 2009
5 | 2 | 3 | 2010
6 | 2 | 3 | 2008
7 | 3 | 2 | 2007
8 | 3 | 3 | 2010
9 | 3 | 3 | 2010
当系列= X时,我需要找到按revision_id分组时最大(年份)的table_id 在 postgresql 中。
例如:当 x =2 时我期望这个结果
table_id | series_id | revision_id | year
------------------------------------------
2 | 2 | 1 | 2009
4 | 2 | 2 | 2009
5 | 2 | 3 | 2010
这不起作用
SELECT * from table
WHERE series_id = 2
AND table_id IN (
SELECT table_id
FROM table
WHERE series_id = 2
GROUP by revision
ORDER BY year DESC
)
我无法找到在 postgresql 中执行此操作的方法,因为我需要返回一个未分组的字段
这里有其他 SQL 风格中的一些类似问题。
MySQL SQL Query, Selecting 5 most recent in each groupSQL 服务器 SQL Server - How to select the most recent record per user?
最佳答案
查询:
SELECT table_id, series_id, revision_id, year
FROM tableName t INNER JOIN
(SELECT revision_id, max(year) AS year
FROM tableName
WHERE series_id = 2
GROUP BY revision_id) s
USING (revision_id, year)
WHERE series_id = 2;
结果:
table_id | series_id | revision_id | year
----------+-----------+-------------+------
2 | 2 | 1 | 2009
4 | 2 | 2 | 2009
5 | 2 | 3 | 2010
(3 rows)
关于用于查找组中最新记录的sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6589649/