我想删除所有重复项,只保留其中一个。
我的查询应该删除所有重复的数据:
cell's contentLabel
答案 0 :(得分:3)
正如Zohar在评论中所述,您的查询将保留 two
重复的行而不是 one
..只保留一行更改您的查询如下..
Check out this question and all its answers有几种方法可以删除像rownumber,group by,self join以及有关何时使用group by vs rownumber的优化提示..
WITH todelete As (
select em.*,
row_number() over (partition by emp_num, [from_date],[to_date],[ req_ser], [ req_year]
order by (select null)) as cnt
from empmission em
)
DELETE FROM todelete
WHERE cnt > 1;
答案 1 :(得分:1)
首先,我建议您不要使用CTE使用临时表作为您的解决方案 使用以下链接找到我为什么这么说
https://dba.stackexchange.com/questions/13112/whats-the-difference-between-a-cte-and-a-temp-table
了解更多使用以下链接
现在让我们回到你的解决方案,我使用了Temp Table
Select e.emp_num,e.from_date,e.to_date,e.[ req_ser],e.[ req_year],COUNT(1) number_of_duplicates
into #temp1 from empmission e
group by emp_num,from_date,to_date,[ req_ser],[ req_year]
Truncate Table empmission
Insert into empmission
Select t.emp_num,
t.from_date,
t.to_date,
t.[ req_ser],
t.[ req_year]
from #temp1 t
Drop Table #temp1 --Droping the temp table
Select * from empmission
或者您可以选择CTE 正如
WITH todelete As (
select em.*,
row_number() over (partition by emp_num, [from_date],[to_date],[ req_ser], [ req_year]
order by (select null)) as cnt
from empmission em
)
DELETE FROM todelete
WHERE cnt > 1;