在提取数据库中重复行的查询结果中仅选择较新的记录
Posted
技术标签:
【中文标题】在提取数据库中重复行的查询结果中仅选择较新的记录【英文标题】:Select only newer records among the result of a query that extracts duplicate rows in a db 【发布时间】:2021-03-20 08:27:19 【问题描述】:我有一个数据库,我可以在其中有多个具有相同字段“帮助”的行(这是一种相同项目的历史变更日志)。 通过以下查询,我将提取具有相同帮助的行,按日期降序排列:
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
这应该是与父层相关的子表(由仅显示最新援助记录的 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 语法,以便显示所有重复行,但日期最新的行除外,这样我就可以拥有如下表:
+------+------------+--------+------+
| 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 |
+------+------------+--------+------+
提前致谢。
【问题讨论】:
【参考方案1】:您可以使用窗口函数来做到这一点。这个想法是通过降序data_ril
对具有相同aid
的记录进行排名,然后过滤掉每个组的顶部记录。
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
【讨论】:
以上是关于在提取数据库中重复行的查询结果中仅选择较新的记录的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Redshift 中仅输出随机 xx% 的查询输出记录?