0

I have a table with the columns: id, relation_id, someData, created_at

I need to select all rows (with all columns, basically SELECT *) that have distinct relation_id AND have the latest created_at date for this specific relation_id.

Example data:

id, relation_id, someData, created_at
1, 123, I am data, 2020-01-01
2, 123, I am data, 2019-01-01
3, 321, I am also data, 2015-01-01
4, 555, Data, 2020-06-05
5, 555, Data, 2011-01-05

Example output:

1, 123, I am data, 2020-01-01
3, 321, I am also data, 2015-01-01
4, 555, Data, 2020-06-05
4

3 回答 3

0

please use below SQL. Row_number window function will rank the data based on order of created_at. filter row number =1 will pick latest row. You can tweak this to choose whatever you want.

SELECT
        id         ,
        relation_id,
        someData   ,
        created_at
FROM
        (
                SELECT
                        id         ,
                        relation_id,
                        someData   ,
                        created_at ,
                        row_number() OVER (PARTITION BY
                                           id, relation_id ORDER BY
                                           id, relation_id, created_at DESC ) rn
                FROM
                        TABLE) rs
WHERE
        rs.rn=1
于 2020-09-16T12:56:43.497 回答
0

distinct relation_id AND have the latest created_at date for this specific relation_id.

Use distinct on:

select distinct on (relation_id) t.*
from t
order by relation_id, created_at desc;

distinct on is a very handy Postgres extension that does exactly what you want.

于 2020-09-16T13:07:37.373 回答
0

I think this will work for you.

SELECT id, relation_id, someData, max(created_at)
GROUP BY id, relation_id, someData
ORDER BY id ASC
于 2020-09-16T13:24:04.027 回答