﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / Article Discussions / Article Discussions by Author / Discuss content posted by Andy Riley  / Using Ranking Functions to Deduplicate Data / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Fri, 24 May 2013 04:22:10 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>[quote][b]PravB4u (7/29/2010)[/b][hr]Hi,I think we can achieve the same without rank function.SELECT * FROM GetMissingItems WHERE RowNumber = 1[/quote]Ummm.... Not without the "Partition By" part of the OVER clause for ROW_NUMBER in what appears to be a missing CTE from your code.</description><pubDate>Thu, 29 Jul 2010 07:27:55 GMT</pubDate><dc:creator>Jeff Moden</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>Hi,I think we can achieve the same without rank function.SELECT * FROM GetMissingItems WHERE RowNumber = 1</description><pubDate>Thu, 29 Jul 2010 05:34:55 GMT</pubDate><dc:creator>PravB4u</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>I'm torn... it's a nicely written article but the premise is at least twice as complicated as it needs to be and 2 times as slow as conventional methods, IMHO.  Don't take my word for it, though... test it yourself... [code="sql"]--===========================================================================--      Create a multi-million row test table.  This is not a measured--      part of the test.--===========================================================================--===== Conditionally drop the test table to make reruns easier     IF OBJECT_ID('TempDB..#AlphaList','U') IS NOT NULL        DROP TABLE #AlphaList;--===== Create and populate a multi-million row test table on the fly SELECT TOP 5000000        AlphaListID = IDENTITY(INT,1,1),        AlphaKey    = CHAR(ABS(CHECKSUM(NEWID()))%26+65) --A thru Z randomly   INTO #AlphaList   FROM Master.sys.All_Columns t1  CROSS JOIN Master.sys.All_Columns t2;--===== Create the expected indexes  ALTER TABLE #AlphaList    ADD PRIMARY KEY CLUSTERED (AlphaListID); CREATE NONCLUSTERED INDEX IX_#AlphaList_AlphaKey     ON #AlphaList (AlphaKey);--===========================================================================--      Test 3 different methods with CPU and Duration measurements.--===========================================================================--===== "Clear the guns"  PRINT REPLICATE('=',80);  PRINT '========== Traditional RowNumber Method ==========';   DBCC FREEPROCCACHE;   DBCC DROPCLEANBUFFERS;    SET STATISTICS TIME ON;--===== Test the codeselect AlphaKeyfrom (        select row_number() over(partition by AlphaKey order by AlphaKey) rownum,         AlphaKey         from #AlphaList ) alwhere rownum = 1        order by AlphaKey;    SET STATISTICS TIME OFF;--===== "Clear the guns"  PRINT REPLICATE('=',80);  PRINT '========== Simple Distinct ==========';   DBCC FREEPROCCACHE;   DBCC DROPCLEANBUFFERS;    SET STATISTICS TIME ON;--===== Test the codeSELECT DISTINCT AlphaKey   FROM #AlphaListORDER BY AlphaKey;    SET STATISTICS TIME OFF;--===== "Clear the guns"  PRINT REPLICATE('=',80);  PRINT '========== New Rank Method from Article ==========';   DBCC FREEPROCCACHE;   DBCC DROPCLEANBUFFERS;    SET STATISTICS TIME ON;--===== Test the codewith AlphaRank(Rank, RowNumber, AlphaKey) as (select   RANK() over (order by AlphaKey) as Rank, ROW_NUMBER() over (order by AlphaKey) as RowNumber, AlphaKeyfrom #AlphaList)select AlphaKeyfrom AlphaRankwhere Rank=RowNumber;    SET STATISTICS TIME OFF;[/code]Here are the results on my 8 year old desktop single p4 CPU running at 1.8Ghz with 1GB of ram on SQL Server 2005 Developer's Edition sp3.[code="plain"](5000000 row(s) affected)========================================================================================== Traditional RowNumber Method ==========DBCC execution completed. If DBCC printed error messages, contact your system administrator.DBCC execution completed. If DBCC printed error messages, contact your system administrator.(26 row(s) affected)SQL Server Execution Times:   CPU time = 2875 ms,  elapsed time = 3005 ms.========================================================================================== Simple Distinct ==========DBCC execution completed. If DBCC printed error messages, contact your system administrator.DBCC execution completed. If DBCC printed error messages, contact your system administrator.(26 row(s) affected)SQL Server Execution Times:   CPU time = 2985 ms,  elapsed time = 3043 ms.========================================================================================== New Rank Method from Article ==========DBCC execution completed. If DBCC printed error messages, contact your system administrator.DBCC execution completed. If DBCC printed error messages, contact your system administrator.(26 row(s) affected)SQL Server Execution Times:   CPU time = 7953 ms,  elapsed time = 8037 ms.[/code]</description><pubDate>Wed, 28 Jul 2010 17:56:27 GMT</pubDate><dc:creator>Jeff Moden</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>I'm disappointed. I've been doing this for a while with ROW_NUMBER and PARTION and it works gr8 in all the situations I've come across.I can't figure out what advantage I can gain using the RANK function.I'm not sure there is an advantage, but I'll be happy if someone corrects me :-)</description><pubDate>Wed, 28 Jul 2010 00:28:44 GMT</pubDate><dc:creator>lgidon</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>I'm still getting ranking functions into my head slowly. :-DNice article about a very useful way to use them.</description><pubDate>Tue, 27 Jul 2010 17:53:06 GMT</pubDate><dc:creator>codebyo</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>Very nice article. Thanks for sharing. My two cents are that I would use the dense_rank() function to return the rank in tandem order. The rank() function tends to skip a rank depending on how many members belong to a group.[code="sql"]declare @AlphaList table (AlphaKey char);insert into @AlphaList(AlphaKey) values ('A');insert into @AlphaList(AlphaKey) values ('A');insert into @AlphaList(AlphaKey) values ('B');insert into @AlphaList(AlphaKey) values ('B');insert into @AlphaList(AlphaKey) values ('C');insert into @AlphaList(AlphaKey) values ('D');insert into @AlphaList(AlphaKey) values ('D');insert into @AlphaList(AlphaKey) values ('E');select  RANK() over (order by AlphaKey) as Rank, dense_RANK() over (order by AlphaKey) as [Rank by density], ROW_NUMBER() over (order by AlphaKey) as RowNumber, AlphaKeyfrom @AlphaList;[/code][code="plain"]Rank	Rank by density	RowNumber	AlphaKey1	1	1	A1	1	2	A3	2	3	B3	2	4	B5	3	5	C6	4	6	D6	4	7	D8	5	8	E[/code]</description><pubDate>Tue, 27 Jul 2010 16:47:41 GMT</pubDate><dc:creator>Langston Montgomery</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>In most of the cases you need to retain the latest record from the duplicates. In that case matching rank=rownumber will not work.So using ROW_NUMBER() partition and ORDER BY col DESC is always a good approach.</description><pubDate>Tue, 27 Jul 2010 12:29:41 GMT</pubDate><dc:creator>Vamshi Bharath</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>Anyone actually check this code?I believe the RANK statement in the CTE is incorrect (see corrected version below) if the intent is to remove duplicates for ItemNumber only.  At the very least, to return the dataset the author provides in the article:777 10.10888 13.13999 16.16Of course, I have to agree with others on this, for this particular example, GROUP with MIN would achieve the same result much more easily.[code="sql"]with GetMissingItems(Rank, RowNumber, ItemNumber, UnitCost) as (	select		--RANK() over (order by ItemNumber, UnitCost) as Rank		RANK() over (order by ItemNumber) as Rank		, ROW_NUMBER() over (order by ItemNumber, UnitCost) as RowNumber		, ItemNumber		, UnitCost	from MissingItems)select	  ItemNumber	, UnitCostfrom GetMissingItemswhere Rank = RowNumber[/code][code="sql"]select	  ItemNumber	, min(UnitCost) 'UnitCost'from #MissingItemsgroup by ItemNumber[/code]</description><pubDate>Tue, 27 Jul 2010 12:27:56 GMT</pubDate><dc:creator>Brian Barkauskas</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>Say for example, if you have type 2 updates and you just wanted to know that which records are the latest in your table, you could do so by using Ranking functions (partitioned over time stamp obviously). If you would have done a distinct on the same table, there is no way to be sure if the record that your distinct query is picking up is indeed the latest one. A very practical example for using ranking functions is the Database Reconciliation process.</description><pubDate>Tue, 27 Jul 2010 10:20:26 GMT</pubDate><dc:creator>rvphx</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>Nice article, but using a one-column table makes people say "Gee, I could do this with SELECT DISTINCT!"  You should have made a case for speed (if any) and the ability to pick entire rows based on matching to a subset of columns. I would also add a "COUNT(*) OVER (PARTITION BY &amp;lt;column list&amp;gt;) AS dup_cnt" to the CTE to give the user some idea of what the data is like</description><pubDate>Tue, 27 Jul 2010 10:01:58 GMT</pubDate><dc:creator>CELKO</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>Don't get me wrong. This is a good example of "how to use RANK() and ROW_NUMBER() functions". My problem is why would I do this instead of using DISTINCT?There is already an article on "Ranking Functions" here...[url=http://www.sqlservercentral.com/articles/T-SQL/69717/][/url]Also, I know that DISTINCT is not the most efficient way to "de-duplicate" (nice phrase) over large datasets. Now if we are saying using Ranking Function approach is faster on larger data sets or largely skewed data sets, i.e. each row is already distinct, then I have learnt something. Else all I have learnt is (yet) one  more way to write (potentially confusing) code. Using DISTINCT on the example cited in the article would be obvious. That's important where I come from.So, if someone can please educate me as to when and why I would use the Ranking function method to get distinct records I would very much appreciate it.</description><pubDate>Tue, 27 Jul 2010 09:47:41 GMT</pubDate><dc:creator>Pagan DBA</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>I find the RANK function to be much better used in situations where I might not be able to group by all fields in the select statement. Another way I have used it before is to find not the latest record, but the SECOND latest record by choosing where RANK = 2.</description><pubDate>Tue, 27 Jul 2010 09:06:12 GMT</pubDate><dc:creator>amenjonathan</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>The approach is/was unique and creative, and for that, it was an excellent article.  But considering there are at least 2 other well known approaches to this problem, I feel that the article was missing the performance comparison that not only compared with the other approaches, but alsoo compared all approaches on a multi-column approach.  Perhaps this was an excellent article as it left me, the reader, wanting lots more :-D</description><pubDate>Tue, 27 Jul 2010 07:44:21 GMT</pubDate><dc:creator>Lambchop4697</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>I personally have used the ranking functions quite a bit lately not to just remove duplicates but to be able to qualify what is removed.  In one case, I needed to qualify one field based on the number of characters in a column and look at another column that may have one of two choices in it - "Reject" or "Reschedule".  In this case, Reject weighed more than Reschedule.  The ranking of both of the columns was added together to come up with the total ranking.  Then all of the rows that were not the highest rank [based on a single column] were removed.</description><pubDate>Tue, 27 Jul 2010 07:14:34 GMT</pubDate><dc:creator>grc-80104</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>Nice article. Gives me another way to de-dupe data. :-)I use almost the same technique, but I have a time stamp associated with each record and this time stamp differs by milliseconds. So I just pick the one which has the latest time stamp. I should point out that when you use Ranking functions on a table that has really large number of records (in my case it was close to 90 millions some times), the query performance can degrade drastically (I didnt even have an index to begin with).</description><pubDate>Tue, 27 Jul 2010 06:42:42 GMT</pubDate><dc:creator>rvphx</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>I also generally use a partitioned row_number(), ordering on some selection criteria (highest number of x with provider y, etc).Is the output of Rank defined by ANSI to always support this method in all implementations?  My guess is that it's only guaranteed to be in order, but that the density of the default invocation could vary.Still, this is clever and hadn't occurred to me before, so thanks for expanding my box.</description><pubDate>Tue, 27 Jul 2010 06:11:18 GMT</pubDate><dc:creator>mross01</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>messineo,If you have multiple columns that you want to deduplicate on you will need to include all of them in whichever method you use.Here is some sample code using each method that should work (all based on the Northwind database).  Note that in all these cases the data will be de-duplicated but which row is selected for each set of duplicates can not be predicted (so if you want the first order for each set you will need different code).[code="plain"]select	a.ProductID	,a.UnitPrice	,a.Quantity	,a.Discountfrom	(select		ProductID		,UnitPrice		,Quantity		,Discount		,Rank() over (order by ProductID,UnitPrice,Quantity,Discount) as Ranking		,Row_Number() over (order by ProductID,UnitPrice,Quantity,Discount) as RowNumber	from		[Order Details]	) as awhere	a.Ranking=a.RowNumber[/code][code="plain"]select	a.ProductID	,a.UnitPrice	,a.Quantity	,a.Discountfrom	(select		ProductID		,UnitPrice		,Quantity		,Discount		,Row_Number() over (partition by ProductID,UnitPrice,Quantity,Discount order by ProductID) as RowNumber	from		[Order Details]	) as awhere	a.RowNumber=1[/code][code="plain"]select	ProductID	,UnitPrice	,Quantity	,Discountfrom	[Order Details]group by	ProductID	,UnitPrice	,Quantity	,Discount[/code]</description><pubDate>Tue, 27 Jul 2010 04:46:21 GMT</pubDate><dc:creator>philip.cullingworth</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>In the example you provided you used one column. Say I have 4 columns and I want to deduplicate based on those. In other words I want to rank against those columns -- how would the SQL statements change?</description><pubDate>Tue, 27 Jul 2010 04:32:41 GMT</pubDate><dc:creator>messineo</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>I had to remove unitprice from the orderby to get deduplicated results.[code="sql"]declare @TempTable table (itemnumber int, unitprice decimal(18, 2));insert into @TempTable values(777, 10.10), (777, 11.11),(777, 12.12),(888, 13.13),(888, 14.14),(888, 15.15),(999, 16.16),(999, 17.17),(999, 18.18);with GetMissingItems(Rank, RowNumber, ItemNumber, UnitCost) as(	select		RANK() over (order by ItemNumber) as Rank,		ROW_NUMBER() over (order by ItemNumber) as RowNumber,		itemnumber,		unitprice	from @TempTable		) select * from GetMissingItemswhere Rank = RowNumber;[/code]</description><pubDate>Tue, 27 Jul 2010 04:05:49 GMT</pubDate><dc:creator>Bhavesh-1094084</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>I agree. The simplest way to deduplicate is using grouping and aggregate functions as needed.regardsÁron</description><pubDate>Tue, 27 Jul 2010 02:54:54 GMT</pubDate><dc:creator>aszendi</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>I was interested to see what the difference in performance between these queries as I would always have used Row_Number with a partition before.On the Northwind database (SQL 2005) I ran the following 2 queries[code="plain"]select	a.ProductID	,a.UnitPricefrom	(select		ProductID		,UnitPrice		,Rank() over (order by ProductID) as Ranking		,Row_Number() over (order by ProductID,UnitPrice) as RowNumber	from		[Order Details]	) as awhere	a.Ranking=a.RowNumberorder by	a.ProductID[/code][code="plain"]select	a.ProductID	,a.UnitPricefrom	(select		ProductID		,UnitPrice		,Row_Number() over (partition by ProductID order by UnitPrice) as RowNumber	from		[Order Details]	) as awhere	a.RowNumber=1order by	a.ProductID[/code]In the Actual Execution Plan, the first query showed up as 64% and the second as 36%.Far from exhaustive, but I'll probably stick to Row_Number with Partition by.In (partial) answer to Phil Wood, if all I wanted was the lowest price for each product then I would use grouping, I'd probably use this method if I wanted to find the customer or order date as well, changing the code to[code="plain"]select	a.ProductID	,a.UnitPrice	,b.CustomerID	,b.OrderDatefrom	(select		ProductID		,UnitPrice		,OrderID		,Row_Number() over (partition by ProductID order by UnitPrice) as RowNumber	from		[Order Details]	) as a		inner join	Orders as b		on			a.OrderID=b.OrderIDwhere	a.RowNumber=1order by	a.ProductID[/code]</description><pubDate>Tue, 27 Jul 2010 02:31:23 GMT</pubDate><dc:creator>philip.cullingworth</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>How about good ol' grouping to remove duplicates and supply any of the minimum, maximum, sum, count, average, etc. etc?select ItemNumber, min(UnitCost) as MinCost from MissingItemsgroup by ItemNumber;ItemNumber	MinCost777	10.10888	13.13999	16.16</description><pubDate>Tue, 27 Jul 2010 01:55:44 GMT</pubDate><dc:creator>phil.wood 94423</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>with the A,B,C,D,E example, the select distinct syntax would be better imho.</description><pubDate>Tue, 27 Jul 2010 01:35:12 GMT</pubDate><dc:creator>david.skov</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>yep, i too use this query to remove duplicates...was wondering, which query is faster, this one or the one mentioned in the article...[quote][b]scottm30 (7/26/2010)[/b][hr]Nice article, thanks for sharing.  The same thing can be achieved with just the row_number function as well.[code="sql"]select AlphaKeyfrom (	select row_number() over(partition by AlphaKey order by AlphaKey) rownum, 	AlphaKey 	from @AlphaList ) alwhere rownum = 1	order by 1;[/code][/quote]</description><pubDate>Tue, 27 Jul 2010 00:50:36 GMT</pubDate><dc:creator>ziangij</dc:creator></item><item><title>RE: Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>Nice article, thanks for sharing.  The same thing can be achieved with just the row_number function as well.[code="sql"]select AlphaKeyfrom (	select row_number() over(partition by AlphaKey order by AlphaKey) rownum, 	AlphaKey 	from @AlphaList ) alwhere rownum = 1	order by 1;[/code]</description><pubDate>Mon, 26 Jul 2010 23:19:28 GMT</pubDate><dc:creator>scottm30</dc:creator></item><item><title>Using Ranking Functions to Deduplicate Data</title><link>http://www.sqlservercentral.com/Forums/Topic959167-2748-1.aspx</link><description>Comments posted to this topic are about the item [B]&lt;A HREF="/articles/Deduplicate/70499/"&gt;Using Ranking Functions to Deduplicate Data&lt;/A&gt;[/B]</description><pubDate>Mon, 26 Jul 2010 20:57:54 GMT</pubDate><dc:creator>andrew.riley</dc:creator></item></channel></rss>