开发者

sql for finding most recent record in a group

开发者 https://www.devze.com 2023-03-18 01:25 出处:网络
i have a table like such table_id | series_id | revision_id | year ------------------------------------------

i have a table like such

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       开发者_JAVA百科  | 2           | 2007
8        | 3         | 3           | 2010
9        | 3         | 3           | 2010

I need to find the table_id for the max(year) when grouped by revision_id when series = X in postgresql.

eg : when x =2 i expect this result

table_id | series_id | revision_id | year
------------------------------------------
2        | 2         | 1           | 2009
4        | 2         | 2           | 2009
5        | 2         | 3           | 2010

this doesn't work

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
)

I cannot figure out a way to do this in postgresql since I need to return a field i am not grouping by

here are some similar problems in other SQL flavors.

MySQL SQL Query, Selecting 5 most recent in each group

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


Query:

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;

Result:

 table_id | series_id | revision_id | year
----------+-----------+-------------+------
        2 |         2 |           1 | 2009
        4 |         2 |           2 | 2009
        5 |         2 |           3 | 2010
(3 rows)


Hmm... Try this:

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号