sql用于查找组中的最新记录

时间:2011-07-05 22:39:10

标签: sql database postgresql

我有一张像这样的表

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

当series = X时,我需要找到由revision_id分组的max(year)的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 group

SQL SERVER SQL Server - How to select the most recent record per user?

2 个答案:

答案 0 :(得分:3)

查询:

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)

答案 1 :(得分:2)

嗯... 试试这个:

SELECT *
FROM table as a
WHERE series_id = ?
AND year = (SELECT MAX(year)
            FROM table as b
            WHERE a.series_id = b.series_id
            AND a.revision_id = b.revision_id)