【问题标题】:Delete rows from the table, keeping the most recent ones [closed]从表中删除行,保留最近的行[关闭]
【发布时间】:2019-03-15 01:45:41
【问题描述】:

我有一个 Oracle 数据表,其中包含重复的唯一 ID 但日期不同。

我想删除表中数据不是最新日期的所有信息,因此,例如,如果 circuit_id 有 70 个输入所有不同的日期,我只想保留一个最接近今天的日期。

例子

select circuit_id, date 
from table_name

circuit_id|date
ABCD123 | 22/04/2018
ABCD123 | 10/10/2018
EFGH321 | 20/01/2018
EFGH321 | 08/10/2018

我正在建立一个查询,它将删除所有重复项,将日期最接近今天日期的 1 输入保留,然后删除其余的,这样输出就会像这样。

circuit_id | date
ABCD123 | 10/10/2018
EFGH321 | 08/10/2018

【问题讨论】:

  • 这个措辞不好,因此很难提供答案。
  • 我正在使用 Oracle SQL

标签: sql oracle duplicates


【解决方案1】:

随便写

delete * from tableName where date="Date"

【讨论】:

  • 该表有超过 20,000 行,我无法为每个要删除的日期执行此操作
【解决方案2】:

这个查询:

select circuit_id, "DATE" 
from (
  select circuit_id, "DATE", 
         row_number() over (partition by circuit_id 
                            order by abs(sysdate - "DATE")) as rn
  from table_name
)
where rn > 1

返回除“最近”日期之外的所有日期 - 因此基本上是您要删除的所有 cicruit_id/“DATE” 组合。

上述查询可用作 IN 运算符对 DELETE 语句的输入:

delete from table_name
where (circuit_id, "DATE") in (
                            select circuit_id, "DATE" 
                            from (
                              select circuit_id, "DATE", 
                                     row_number() over (partition by circuit_id 
                                                        order by abs(sysdate - "DATE")) as rn
                              from table_name
                            )
                            where rn > 1);

【讨论】:

  • 这正是我想要的,感谢您花时间给我这个解决方案
猜你喜欢
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 2013-04-08
相关资源
最近更新 更多