Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Select Duplicate Values using Distinct, Not Exists, CTE, Union

I need to select duplicate values highlighted in green from the Object table show below: Object table

I've tried different combination of the code below. But cannot return the two duplicate rows.

;with CTE as
    (Select distinct ID, count([Object ID]) as [Object ID] 
from #Object 
     group by ID having count([Object ID]) > 1)

select * from CTE where 
    NOT EXISTS (Select distinct ID , count(distinct [Object ID]) as [Object ID] 
from #Object group by ID having count(distinct [Object ID]) > 1);
like image 389
Data Engineer Avatar asked Mar 22 '26 15:03

Data Engineer


2 Answers

You can use the window function ROW_NUMBER() to identify duplicate rows.

Declare @YourTable table (ID int,ObjectID int,ObjectName varchar(50))
Insert into @YourTable values
(250708,321,'hotel'),
(250708,343,'mercantile'),
(250708,370,'parking'),
(250708,370,'residential condominium'),
(250708,370,'residential condominium'),
(250708,401,'residential condominium'),
(250708,401,'residential condominium')



;with cte as (
    Select *
          ,RN = Row_Number() over ( Partition By ID,ObjectID,ObjectName Order by (Select NULL))
     From  @YourTable
)
Select * 
 From cte 
 Where RN>1

Returns

enter image description here

On a side-note, you can delete these records by replacing the final Select * with DELETE

like image 168
John Cappelletti Avatar answered Mar 25 '26 04:03

John Cappelletti


Below is the correct edition of the code in the first answer

;With cte as (
        Select *
              ,RN = Row_Number() over (Partition By ID, [Object ID] Order by (Select NULL))
       From tblObject 
     )

    Select *
     From cte 
     Where RN>1;
like image 38
Data Engineer Avatar answered Mar 25 '26 03:03

Data Engineer



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!