首先我建議你不要使用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;
其實,這應該留下一式兩份。你的where子句應該是'WHERE cnt> 1'。 –