2017-01-03 269 views
1

我列出重複如下:刪除重複

select s.MessageId, t.* 
from Message s 
join (
    select ToUserId, FromUserId, count(*) as qty 
    from Message 
    group by ToUserId, FromUserId 
    having count(*) > 1 
) t on s.ToUserId = t.ToUserId and s.FromUserId = t.FromUserId 

現在,我怎麼刪除所有,但消息中的一個(我想刪除重複這樣我就可以申請一個獨特的索引FromUserId and ToUserId)。

+0

[卸下重複行(基於從多個列中的值)從SQL表]的可能的複製(http://stackoverflow.com/questions/30243945/removing-duplicate-rows-based-on- values-from-multiple-columns-from-sql-table) – FuzzyTree

+0

@FuzzyTree爲什麼你會投票結束,如果有已經有用的答案? – SB2055

+0

因爲它仍然是一個重複的問題和重複的問題雜亂的網站,沒有提供任何價值未來的遊客 – FuzzyTree

回答

5

使用cte並分配行號,以便可以刪除除重複對之外的所有對。

with rownums as 
(select m.*, 
row_number() over(partition by ToUserId, FromUserId order by ToUserId, FromUserId) as rnum 
from Message m) 
delete r 
from rownums r 
where rnum > 1 
0

製作試樣數據

DECLARE @Message TABLE(ID INT ,ToUserId varchar(100),FromUserId varchar(100)) 
    INSERT INTO @Message(ID,ToUserId, FromUserId) 
    VALUES (1,'abc', 'def' ), (2,'abc', 'def' ), (3,'abc', 'def' ), (4,'qaz', 'xsw' ) 

--Do刪除數據

DELETE m FROM @Message AS m 
    INNER JOIN (
     SELECT *,row_number()OVER(PARTITION BY ToUserId,FromUserId ORDER BY ID) AS rn FROM @Message AS m 
    ) t ON t.ID=m.ID 
    WHERE t.rn>1 

    SELECT * FROM @Message 
 
----------- ---------- ---------- 
1   abc  def 
4   qaz  xsw 

如果沒有列指示指定行ID,就可以嘗試使用行的地址(例如%% lockres% %)

DELETE m FROM @Message AS m 
    INNER JOIN (
     SELECT *,row_number()OVER(PARTITION BY ToUserId,FromUserId ORDER BY %%lockres%%) AS rn FROM @Message AS m 
    ) t ON t.ID=m.ID 
    WHERE t.rn>1 

    SELECT *, %%lockres%% FROM @Message