Select 在数据库中提取重复行的查询结果中只有较新的记录

Select only newer records among the result of a query that extracts duplicate rows in a db

我有一个数据库,其中我可以有多行具有相同的字段“援助”(这是一种相同项目的历史变更日志)。 通过以下查询,我将提取具有按降序日期排序的相同辅助信息的行:

select aid,data_ril,specie,id from scu.censimento t1
where (select count(*) from scu.censimento t2
where t1.aid = t2.aid) > 1
order by aid, data_ril desc

应该是父层相关的子层table(由只显示最新援助记录的postgres实体化视图制作),以下是我得到的结果:

    +------+------------+--------+------+
    | aid  | data_ril   | specie | id   |
    +------+------------+--------+------+
    | 349  | 2020-06-18 | 35     | 349  |
    +------+------------+--------+------+
    | 349  | 2020-06-17 | 35     | 2004 |
    +------+------------+--------+------+
    | 700  | 2020-08-07 | 58     | 700  |
    +------+------------+--------+------+
    | 700  | 2020-07-06 | 58     | 2006 |
    +------+------------+--------+------+
    | 700  | 2020-05-02 | 15     | 1956 |
    +------+------------+--------+------+
    | 1316 | 2020-09-02 | 1      | 1316 |
    +------+------------+--------+------+
    | 1316 | 2020-08-27 | 1      | 2005 |
    +------+------------+--------+------+
    | 1317 | 2020-09-02 | 2      | 1317 |
    +------+------------+--------+------+
    | 1317 | 2020-08-27 | 2      | 1996 |
    +------+------------+--------+------+
    | 1481 | 2020-12-03 | 21     | 2112 |
    +------+------------+--------+------+
    | 1481 | 2020-09-08 | 49     | 1481 |
    +------+------------+--------+------+
    | 1492 | 2020-09-28 | 6      | 1492 |
    +------+------------+--------+------+
    | 1492 | 2020-09-08 | 6      | 1999 |
    +------+------------+--------+------+
    | 1688 | 2020-11-03 | 72     | 1688 |
    +------+------------+--------+------+
    | 1688 | 2020-10-08 | 72     | 2000 |
    +------+------------+--------+------+

我想知道 SQL 语法来修改上面的查询,以便显示除最新日期之外的所有重复行,这样我就可以有一个 table 像以下:

+------+------------+--------+------+
| aid  | data_ril   | specie | id   |
+------+------------+--------+------+
| 349  | 2020-06-17 | 35     | 2004 |
+------+------------+--------+------+
| 700  | 2020-07-06 | 58     | 2006 |
+------+------------+--------+------+
| 700  | 2020-05-02 | 15     | 1956 |
+------+------------+--------+------+
| 1316 | 2020-08-27 | 1      | 2005 |
+------+------------+--------+------+
| 1317 | 2020-08-27 | 2      | 1996 |
+------+------------+--------+------+
| 1481 | 2020-09-08 | 49     | 1481 |
+------+------------+--------+------+
| 1492 | 2020-09-08 | 6      | 1999 |
+------+------------+--------+------+
| 1688 | 2020-10-08 | 72     | 2000 |
+------+------------+--------+------+

提前致谢。

您可以使用 window 函数来做到这一点。思路是将aid相同的记录按data_ril降序排列,然后过滤出每组最靠前的记录。

select aid, data_ril, specie, id
from (
    select t.*, 
        row_number() over(partition by aid order by data_ril desc) rn
    from mytable t 
) t
where rn > 1
order by aid, data_ril