从表中删除行,保留最新行

时间:2018-10-10 07:53:53

标签: sql oracle duplicates

我有一个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

我正在寻找一个查询,它将删除所有重复项,将第一个输入保留在日期最接近当前日期的地方,然后删除其余的,这样输出将是这样。

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

2 个答案:

答案 0 :(得分:0)

此查询:

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”组合。

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

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);

答案 1 :(得分:-1)

只写

delete * from tableName where date="Date"