Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Duplicates using Rank Over Partition

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] 
like image 440
Internet Engineer Avatar asked Sep 27 '11 13:09

Internet Engineer


People also ask

Can we use partition by in rank function?

To partition rows and rank them by their position within the partition, use the RANK() function with the PARTITION BY clause. SQL's RANK() function allows us to add a record's position within the result set or within each partition. In our example, we rank rows within a partition.

What is rank () over partition by?

The RANK() function is a window function that assigns a rank to each row in the partition of a result set. The rank of a row is determined by one plus the number of ranks that come before it. RANK() OVER ( PARTITION BY <expr1>[{,<expr2>...}] ORDER BY <expr1> [ASC|DESC], [{,<expr2>...}] )

How do I find exact duplicates in SQL?

One way to find duplicate records from the table is the GROUP BY statement. The GROUP BY statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has the same values in different rows then it will arrange these rows in a group.


1 Answers

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]
like image 60
Lamak Avatar answered Oct 02 '22 05:10

Lamak