SQL Server标识所有重复的行

时间:2016-10-10 22:19:35

标签: sql-server duplicates row

我在表格中有这些信息:

id  Value   Date        Amount
------------------------------
1   79111   2016-10-10  700.00
2   79111   2016-10-10  800.00
3   79111   2016-10-12  900.00
4   79111   2016-10-10  500.00
5   79111   2016-10-27  100.00

我想识别具有相同日期信息的所有行,如下所示:

id  Value   Date        Amount  Alert
----------------------------------------
1   79111   2016-10-10  700.00  duplicate
2   79111   2016-10-10  800.00  duplicate
3   79111   2016-10-12  900.00  NULL
4   79111   2016-10-10  500.00  duplicate
5   79111   2016-10-27  100.00  NULL

我已经完成了识别“X”行的重复行...但我需要将“X”行标识为重复记录。我的问题:

WITH CTE AS
(
SELECT *,RN=ROW_NUMBER() OVER (PARTITION BY Value_my, Date_my ORDER BY id DESC) FROM myTable
)
select *
from CTE A
where A.RN>1 Or A.RN = 1

但我有这个:

id  Value   Date        Amount  Alert
----------------------------------------
1   79111   2016-10-10  700.00  NULL ***How identify this row?***
2   79111   2016-10-10  800.00  duplicate
3   79111   2016-10-12  900.00  NULL
4   79111   2016-10-10  500.00  duplicate
5   79111   2016-10-27  100.00  NULL

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

这不仅可以识别重复的记录,还可以识别它们是哪些记录。

Declare @Yourtable table (ID int,value int,Date date,Amount money) 
Insert into @Yourtable values 
(1,79111,'2016-10-10',700.00),
(2,79111,'2016-10-10',800.00),
(3,79111,'2016-10-12',900.00),
(4,79111,'2016-10-10',500.00),
(5,79111,'2016-10-27',100.00)

Select A.*
      ,Alert = case when B.DuplicateOf is null then Null else 'Alert' end
      ,B.DuplicateOf 
 From  @YourTable A
 Cross Apply (Select DuplicateOf = Stuff((Select Distinct ',' + cast(id as varchar(25)) 
                              From @YourTable 
                              Where id<>A.id
                                and value=A.value
                                and date =A.date
                                For XML Path ('')),1,1,'')
              ) B
 --Where Dupes is not null

<强>返回

ID  value   Date        Amount  Alert   DuplicateOf
1   79111   2016-10-10  700.00  Alert   2,4
2   79111   2016-10-10  800.00  Alert   1,4
3   79111   2016-10-12  900.00  NULL    NULL
4   79111   2016-10-10  500.00  Alert   1,2
5   79111   2016-10-27  100.00  NULL    NULL

答案 1 :(得分:0)

感谢@ john-cappelletti,我找到了一个基于jhon答案的解决方案:

$SqlServer
相关问题