首页 > 解决方案 > Distinct selection by one of values with a condition

问题描述

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

标签: sqlpostgresql

解决方案


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

推荐阅读