SQL:使用Distinct,Not Exists,CTE,Union选择重复值

时间:2017-01-12 22:08:02

标签: sql-server duplicates union common-table-expression not-exists

我需要从下面的Object表中选择以绿色突出显示的重复值: Object table

我尝试过以下代码的不同组合。但是不能返回两个重复的行。

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

2 个答案:

答案 0 :(得分:7)

您可以使用窗口函数ROW_NUMBER()来识别重复的行。

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

返回

enter image description here

在旁注中,您可以将最终Select *替换为DELETE

来删除这些记录

答案 1 :(得分:2)

以下是第一个答案中正确版本的代码

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