我有以下SQL选择。如何将其转换为删除语句,以便保留其中一行但删除重复?
select s.ForsNr, t.*
from [testDeleteDublicates] s
join (
select ForsNr, period, count(*) as qty
from [testDeleteDublicates]
group by ForsNr, period
having count(*) > 1
) t on s.ForsNr = t.ForsNr and s.Period = t.Period
答案 0 :(得分:0)
尝试使用以下内容:
方法1:
DELETE FROM Mytable WHERE RowID NOT IN (SELECT MIN(RowID) FROM Mytable GROUP BY Col1,Col2,Col3)
方法2:
;WITH cte
AS (SELECT ROW_NUMBER() OVER (PARTITION BY ForsNr, period
ORDER BY ( SELECT 0)) RN
FROM testDeleteDublicates)
DELETE FROM cte
WHERE RN > 1
希望这有帮助!
注意:强> 请更改表格&列名称根据您的需要!
答案 1 :(得分:0)
只要您有一个生成的主键列(这是一个好主意),这很容易。您只需选择每个重复组的min(id)并删除其他所有内容 - 请注意,我已删除了having子句,以便从重复中排除非重复行的ID。
delete from [testDeleteDublicates]
where id not in (
select Min(Id) as Id
from [testDeleteDublicates]
group by ForsNr, period
)
如果你没有人工主键,你可能必须使用行号来达到同样的效果,因为它们的实现因供应商而异。
答案 2 :(得分:0)
您可以使用2选项。
' 2。将row_number()与分区选项一起使用,运行时向每行添加行,然后删除重复的行。
Removing duplicates using partition by SQL Server
--give group by field in partition.
;with cte(
select ROW_NUMBER() over( order by ForsNr, period partition ForsNr, period) RowNo , * from [testDeleteDublicates]
group by ForsNr, period
having count(*) > 1
)
select RowNo from cte
group by ForsNr, period