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]
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.
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>...}] )
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With