保存首先创建的行

时间:2017-07-10 14:27:01

标签: java oracle

以下是我的表DUMMY_TBL的状态 enter image description here

我正在编写一个查询来保存先创建的行并删除其余的行。分组可以基于LOCAL_ID完成,因此在这种情况下,查询应该保留第一行和第四行并删除其余部分。如果我们查看WHENCREATED列,我们就可以获得有关行的创建详细信息的信息。

到目前为止,我所做的是

select min(WHENCREATED),LOCAL_ID from DUMMY_TBL group by local_ID;

但这只给了我{min} WHENCREATED日期和LOCAL_ID。但是,我不确定如何继续进行。 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

从提取记录的查询中保留:

select local_id, min(whencreated) as earliest
from dummy_tbl
group by local_id;

然后组合删除除要保留的记录之外的所有其他记录:

delete from dummy_tbl
where (local_id, whencreated)
not in
(    
    select local_id, min(whencreated) as earliest
    from dummy_tbl
    group by local_id
);

请记住,对于更大的表,这可能不起作用,因为in子句有大小限制

答案 1 :(得分:0)

收集MinDate / LOCAL_ID组合并将它们连接到实际表格。

WITH CTE
AS (
    SELECT min(WHENCREATED) AS MinDate
        ,LOCAL_ID
    FROM DUMMY_TBL
    GROUP BY local_ID
    )

DELETE
FROM DUMMY_TBL
JOIN CTE c ON c.MinDate != WHENCREATED
    AND c.LOCAL_ID = LOCAL_ID