想象一下,我有这样一张桌子:
Nr Date
2162416 14.02.2014
2162416 11.08.2006
2672007 13.04.2016
2672007 27.11.2007
3030211 31.01.2013
3030211 25.04.2006
3108243 11.04.2016
3108243 24.08.2009
3209248 05.04.2016
3209248 08.06.2012
3232333 11.04.2012
3232333 23.12.2011
3232440 08.04.2013
3232440 23.01.2008
如您所见,条目是仅在日期列的值上不同的对。如何通过比较日期删除其中一个。我想删除旧的。
只能有两行具有相同的Nr
答案 0 :(得分:3)
简单来说,如果存在具有相同Nr但后来日期的另一行,请使用EXISTS
删除行:
delete from tablename t1
where exists (select 1 from tablename t2
where t2.nr = t1.nr
and t2.date > t1.date)
可替换地:
delete from tablename
where (nr, date) not in (select nr, max(date) from tablename group by nr)
答案 1 :(得分:2)
如果您总是有成对的行,则可以使用:
delete your_table
where (nr, date) in (
select nr, min(date)
from your_table
group by nr
)
如果要处理只有一行的情况,可以添加条件:
delete your_table
where (nr, date) in (
select nr, min(date)
from your_table
group by nr
having count(1) > 1
)
答案 2 :(得分:1)
使用公用表表达式(CTE)的方法:
DELETE FROM your_table
WHERE (nr, date) IN
(
WITH x AS
(
SELECT nr, date,
ROW_NUMBER() OVER (PARTITION BY nr ORDER BY date DESC) AS n
FROM your_table
)
SELECT nr, date
FROM x
WHERE n > 2
);