Find Duplicates using Rank Over Partition

2019-05-01 23:58发布

问题:

The following SQL works in identifying unique phones when there is a disparity in LastDate. But if duplicate phones have the exact same LastDate it does not work.

Any ideas will be appreciate it.

SELECT * FROM
 (
  SELECT  ID, Phone, [LastDate]
  ,RANK() OVER (PARTITION BY Phone ORDER BY [LastDate]) AS 'RANK',                          
            COUNT(Phone) OVER (PARTITION BY  Phone) AS 'MAXCOUNT'
              FROM MyTable          
              WHERE Groupid = 5
              ) a
              WHERE [RANK] = [MAXCOUNT] 

回答1:

Change the RANK for ROW_NUMBER.

SELECT * 
FROM  (   SELECT    ID, Phone, [LastDate],
                    ROW_NUMBER() OVER (PARTITION BY Phone ORDER BY [LastDate]) AS 'RANK',
                    COUNT(Phone) OVER (PARTITION BY  Phone) AS 'MAXCOUNT'
          FROM MyTable
          WHERE Groupid = 5) a 
WHERE [RANK] = [MAXCOUNT]