Oracle Dense_rank
Oracle Dense Rank
我需要根据ID和时间删除重复的行column.I需要保留最新时间的记录only.If有两条记录的最大时间,我可以保留任何一条记录并删除其中的所有其他记录 group.Please 在下面找到我的输入数据
ID TIMES
123 13/01/2018
123 14/01/2018
123 15/01/2018
345 14/01/2018
567 20/01/2018
567 20/01/2018
879 NULL
879 21/01/2018
我已经为 same.But 编写了一个查询,它不适用于 ID=567 的情况,因为它们在时间列中具有相同的值。请在下面找到我的查询
delete FROM table where (ID,times) in(
SELECT ID,times,
RANK() OVER (PARTITION BY ID ORDER BY times DESC NULLS LAST) dest_rank
FROM TABLE
) WHERE dest_rank <> 1
有什么办法可以做到这一点。
这是一种方法:
delete t from t
where rowid <> (select max(rowid) keep (dense_rank first order by times desc)
from t t2
where t2.id = t.id
);
不过,我会用一个临时的 table:
create temporary table tt
select id, max(times) as times
from t
group by id;
truncate table t;
insert into t(id, times)
select id, times
from tt;
您可以通过贡献或rowid
:
获得成功
delete mytable where (rowid) in
(
select t1.rowid from mytable t1
where times <
(
select max(times)
from mytable t2
where t2.id = t1.id
and t2.times != t1.times -- for non-matching records of times
)
union all
select t1.rowid from mytable t1
where rowid <
(
select max(rowid)
from mytable t2
where t2.id = t1.id
and t2.times = t1.times -- for matching records of times
)
);
我会
delete demo where rowid in
( select lag(rowid) over (partition by id order by times nulls first) from demo );
您没有说明您希望如何处理空值。如果您想保留空日期的行,请将 nulls first
更改为 nulls last
。
我需要根据ID和时间删除重复的行column.I需要保留最新时间的记录only.If有两条记录的最大时间,我可以保留任何一条记录并删除其中的所有其他记录 group.Please 在下面找到我的输入数据
ID TIMES
123 13/01/2018
123 14/01/2018
123 15/01/2018
345 14/01/2018
567 20/01/2018
567 20/01/2018
879 NULL
879 21/01/2018
我已经为 same.But 编写了一个查询,它不适用于 ID=567 的情况,因为它们在时间列中具有相同的值。请在下面找到我的查询
delete FROM table where (ID,times) in(
SELECT ID,times,
RANK() OVER (PARTITION BY ID ORDER BY times DESC NULLS LAST) dest_rank
FROM TABLE
) WHERE dest_rank <> 1
有什么办法可以做到这一点。
这是一种方法:
delete t from t
where rowid <> (select max(rowid) keep (dense_rank first order by times desc)
from t t2
where t2.id = t.id
);
不过,我会用一个临时的 table:
create temporary table tt
select id, max(times) as times
from t
group by id;
truncate table t;
insert into t(id, times)
select id, times
from tt;
您可以通过贡献或rowid
:
delete mytable where (rowid) in
(
select t1.rowid from mytable t1
where times <
(
select max(times)
from mytable t2
where t2.id = t1.id
and t2.times != t1.times -- for non-matching records of times
)
union all
select t1.rowid from mytable t1
where rowid <
(
select max(rowid)
from mytable t2
where t2.id = t1.id
and t2.times = t1.times -- for matching records of times
)
);
我会
delete demo where rowid in
( select lag(rowid) over (partition by id order by times nulls first) from demo );
您没有说明您希望如何处理空值。如果您想保留空日期的行,请将 nulls first
更改为 nulls last
。