在sql server中过滤两个连续的行号

时间:2017-05-25 03:49:24

标签: sql-server tsql row-number

我正在使用此代码查找重复项

代码:

select donrId,
    donrFirstName,
    donrLastName,
    donrBirthDate,
    ROW_NUMBER() over (
        partition by donrFirstName,
        donrBirthDate order by donrLastName
        ) as SequenceNumber
from donors ) as dd
where dd.SequenceNumber > 1
order by donrId

问题:

我不能在两个连续的数字上过滤分区结果集,例如1和2

期望的结果:

donrFirstName   |donrLastName  |donrBirthDate   |SequenceNumber 
---------------------------------------------------------------
king            |kong          |25/05/2017      |1
king            |kong          |25/05/2017      |2

1 个答案:

答案 0 :(得分:0)

您的查询将仅返回序列号为>的记录。 1.要返回以数字1开头的所有记录,您可以使用COUNT(*)窗口功能,如下所示:

SELECT 
    donrId, donrFirstName, donrLastName, donrBirthDate, SequenceNumber
FROM
    (SELECT 
         donrId, donrFirstName, donrLastName, donrBirthDate, 
         ROW_NUMBER() OVER (PARTITION BY donrFirstName, donrBirthDate ORDER BY donrLastName) AS SequenceNumber 
         COUNT(*) OVER (PARTITION BY donrFirstName, donrBirthDate) AS cnt
     FROM 
         donors) AS dd 
WHERE 
    dd.cnt > 1 
ORDER BY 
    donrId