Login or Sign Up to become a member!
LessThanDot Site Logo

LessThanDot

Community Wiki

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.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot facebook Lessthandot rss

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

Navigation

Google Ads

Rank

From Wiki

Jump to: navigation, search

Rank (SQL Server 2000)

What does Rank do? Duplicates are considered and the same values have the same number, however numbers are 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

  1. CREATE TABLE Rankings (Value Char(1))
  2.     INSERT INTO Rankings
  3.     SELECT 'A' UNION ALL
  4.     SELECT 'A' UNION ALL
  5.     SELECT 'B' UNION ALL
  6.     SELECT 'B' UNION ALL
  7.     SELECT 'B' UNION ALL
  8.     SELECT 'C' UNION ALL
  9.     SELECT 'D' UNION ALL
  10.     SELECT 'E' UNION ALL
  11.     SELECT 'F' UNION ALL
  12.     SELECT 'F' UNION ALL
  13.     SELECT 'F'


To do the equivalent of the Rank function in SQL Server 2000 we have to use a temp table with an identity column.

  1. SELECT IDENTITY(INT, 1,1) AS Rank ,Value
  2.     INTO #Ranks FROM Rankings WHERE 1=0
  3.  
  4.     INSERT INTO #Ranks
  5.     SELECT Value FROM Rankings
  6.     ORDER BY Value


After we have the values in the table it is as simple as this:

  1. SELECT z.Ranking ,t2.Value
  2.     FROM (SELECT MIN(t1.Rank) AS Ranking,t1.Value FROM #Ranks t1 GROUP BY t1.Value) z
  3.     JOIN #Ranks t2 ON z.Value = t2.Value
  4.     ORDER BY z.Ranking


Rank (SQL Server 2005/2008)

We are starting out by creating a table

  1. CREATE TABLE Rankings (Value Char(1),id INT)
  2.     INSERT INTO Rankings
  3.     SELECT 'A',1 UNION ALL
  4.     SELECT 'A',3 UNION ALL
  5.     SELECT 'B',3 UNION ALL
  6.     SELECT 'B',4 UNION ALL
  7.     SELECT 'B',5 UNION ALL
  8.     SELECT 'C',2 UNION ALL
  9.     SELECT 'D',6 UNION ALL
  10.     SELECT 'E',6 UNION ALL
  11.     SELECT 'F',5 UNION ALL
  12.     SELECT 'F',9 UNION ALL
  13.     SELECT 'F',10


And the SQL server 2005/2008 is as simple as

  1. SELECT RANK() OVER ( ORDER BY Value),*
  2.     FROM Rankings


Contributed by: --SQLDenis 02:34, 31 May 2008 (GMT)

Part of SQL Server Programming Hacks

Section Ranking, Max etc

133 Rating: 2.2/5 (77 votes cast)