Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting/Deleting duplicates

I have the below table CatItemLink with the records in it:

ID                                      CatID                                   ItemID
--------------------------------------------------------------------------------------------------------------------
ADBFBEFE-11F4-4CF0-A889-BBC9358CCF57    A411277E-0873-4323-B016-63F4DFA664C2    B66A47DF-A0E3-4D41-88E9-0B0CB27085D7
->E212A458-E5E2-4D77-B618-425082CFD8D2  A411277E-0873-4323-B016-63F4DFA664C2    B66A47DF-A0E3-4D41-88E9-0B0CB27085D7

D071B1C1-7296-4BCA-8AD3-8495704BF679    A411277E-0873-4323-B016-63F4DFA664C2    E288327C-15BF-4B01-BD37-0B6AD5365966
->B4F59516-2D85-4E2A-8FE4-3EDA27C3DA4F  A411277E-0873-4323-B016-63F4DFA664C2    E288327C-15BF-4B01-BD37-0B6AD5365966
->F3FB6BA5-79EC-4FC5-899E-24FA9F8DFF25  A411277E-0873-4323-B016-63F4DFA664C2    E288327C-15BF-4B01-BD37-0B6AD5365966

CF3FBD01-4445-4A72-AD1A-BF397970AEFC    BFB76F3D-4F06-4200-925D-1968666741A3    E288327C-15BF-4B01-BD37-0B6AD5365966

ID is a primary key. [CatID,ItemID] should have been a unique index, but the DBO did not specify that index. How to delete/select the records marked with -> meaning there will be only one ItemID per CatID. (ItemID can be found with different CatID and this is ok).

I have a solution that uses SET ROWCOUNT but I want to have an alternative.

like image 856
kobik Avatar asked May 15 '26 05:05

kobik


1 Answers

;WITH x AS 
( 
  SELECT ID, rn = ROW_NUMBER() OVER 
  (PARTITION BY CatID, ItemID ORDER BY ID)
  FROM dbo.CatItemLink
)
DELETE x WHERE rn > 1;
like image 123
Aaron Bertrand Avatar answered May 17 '26 04:05

Aaron Bertrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!