我对SQL很新,但却无法找到我做错的事情。我试图删除在2个特定列中具有匹配字段的行与同一表中的其他行,对于临时表,以便只有一行保留相同的ID和Year AND,以便保留的行是具有该年度ID的最大日期。
My table:
ID Year Date
----------------------------------------------------
1 2017 01/05/2017
1 2017 11/17/2017
1 2017 08/07/2017
1 2016 03/22/2017
1 2016 04/01/2017
2 2017 03/12/2017
2 2016 02/03/2016
2 2016 04/19/2016
期望的结果:
ID Year Date
----------------------------------------------------
1 2017 11/17/2017
1 2016 04/01/2016
2 2017 03/12/2017
2 2016 04/19/2016
我有什么:
DELETE FROM #Temp
WHERE NOT EXISTS (
SELECT DISTINCT
t1.ID,
t1.Year
FROM #Temp AS t1,
#Temp AS t2
WHERE t1.ID = t2.ID
AND t1.Year <> t2.Year
GROUP BY t1.ID, t1.Year )
当我运行它时,没有任何内容被删除但是当我删除前两行以测试将要删除的内容时,结果是正确的,所以我真的很困惑。我正在研究MAX功能,但希望这部分首先工作。
任何帮助将不胜感激!我不知道它有什么问题。
答案 0 :(得分:0)
with cte as
(
select row_number() over (partition by ID, Year order by date desc) as rn
)
delete * from cte where rn > 1;
答案 1 :(得分:0)
另一种方法是使用row_number()
函数根据ID
查找重复记录。Year
delete t from
(
select *, row_number() over (partition by ID, [Year] order by date desc) rn from <table>
) t where t.rn > 1