2016-07-31 144 views
0

我想刪除所有重複項只保留其中一個。如何刪除所有重複項只保留其中一個

我的查詢應該刪除所有重複的數據:

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 > 2; 
+3

其實,這應該留下一式兩份。你的where子句應該是'WHERE cnt> 1'。 –

回答

1

首先我建議你不要使用CTE使用臨時表爲您的解決方案 使用下面的鏈接,找到爲什麼我是個說這

https://dba.stackexchange.com/questions/13112/whats-the-difference-between-a-cte-and-a-temp-table

瞭解更多使用下面的鏈接

http://www.dotnet-tricks.com/Tutorial/sqlserver/X517150913-Difference-between-CTE-and-Temp-Table-and-Table-Variable.html

現在讓我們回到你的解決方案,我已經使用臨時表

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; 
3

正如評論通過Zohar的規定,您的查詢將保持two重複行不one ..To只保留一個行更改查詢像下面..

Check out this question and all its answers幾種方式刪除像rownumber,group by,自我加入,還優化提示何時使用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; 
相關問題