我尝试过以下代码的不同组合。但是不能返回两个重复的行。
;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);
答案 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
返回
在旁注中,您可以将最终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;