当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《SQL:使用Distinct,NotExists,CTE,Union选择重复值》经验,为你挑选了1个好方法。

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

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

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

John Cappell.. 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> John Cappell..:

您可以使用窗口函数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

推荐阅读
ifx0448363
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有