Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Dense Rank
From Wiki
Dense_Rank(SQL Server 2000)
What does Rank do? Duplicates are considered and same values have the same number, numbers are not skipped Since SQL Server 2000 doesn't have the windowing functions which are available in SQL server 2005 we have to take a different approach.
First create this table
- CREATE TABLE Rankings (VALUE CHAR(1))
- INSERT INTO Rankings
- SELECT 'A' UNION ALL
- SELECT 'A' UNION ALL
- SELECT 'B' UNION ALL
- SELECT 'B' UNION ALL
- SELECT 'B' UNION ALL
- SELECT 'C' UNION ALL
- SELECT 'D' UNION ALL
- SELECT 'E' UNION ALL
- SELECT 'F' UNION ALL
- SELECT 'F' UNION ALL
- SELECT 'F'
To do the equivalent of the Dense_Rank function in SQL Server 2000 we have to use a temp table with an identity column.
- SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
- INTO #Ranks FROM Rankings WHERE 1=0
- INSERT INTO #Ranks
- SELECT VALUE FROM Rankings
- ORDER BY VALUE
After we have the values in the table it is as simple as this:
- SELECT x.Ranking ,x.VALUE
- FROM (SELECT (SELECT COUNT( DISTINCT t1.VALUE) FROM Rankings t1 WHERE z.Value>= t1.VALUE)AS Ranking, z.VALUE
- FROM #Ranks z ) x
- ORDER BY x.Ranking
Dense_Rank(SQL Server 2005/2008)
We are starting out by creating a table
- CREATE TABLE Rankings (VALUE CHAR(1),id INT)
- INSERT INTO Rankings
- SELECT 'A',1 UNION ALL
- SELECT 'A',3 UNION ALL
- SELECT 'B',3 UNION ALL
- SELECT 'B',4 UNION ALL
- SELECT 'B',5 UNION ALL
- SELECT 'C',2 UNION ALL
- SELECT 'D',6 UNION ALL
- SELECT 'E',6 UNION ALL
- SELECT 'F',5 UNION ALL
- SELECT 'F',9 UNION ALL
- SELECT 'F',10
And the SQL server 2005/2008 is as simple as
- SELECT DENSE_RANK() OVER ( ORDER BY VALUE),*
- FROM Rankings
Contributed by: --SQLDenis 02:35, 31 May 2008 (GMT)
Part of SQL Server Programming Hacks
Section Ranking, Max etc



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.