Difference between revisions of "RANK"

From SQLZOO
Jump to navigation Jump to search
Line 32: Line 32:
 
You can see view the RANK according to continent. This shows the biggest country
 
You can see view the RANK according to continent. This shows the biggest country
 
<source lang='sql' class='def e-oracle e-mssql'>
 
<source lang='sql' class='def e-oracle e-mssql'>
SELECT name,population,
+
SELECT
      RANK() OVER (ORDER BY population DESC) AS world_rank,
+
name,population,
      RANK() OVER (PARTITION BY continent ORDER BY population DESC) continent_rank
+
RANK() OVER (ORDER BY population DESC) AS world_rank,
      AS r
+
RANK() OVER (PARTITION BY continent ORDER BY population DESC)  
 +
            AS local_rank
 
FROM world WHERE population>100000000
 
FROM world WHERE population>100000000
 
ORDER BY name
 
ORDER BY name

Revision as of 08:41, 5 July 2017

Compatibility
RANK() OVER (ORDER BY f DESC)
EngineOKAlternative
ingresNo
mysqlNo
oracleYes
postgresNo
sqlserverYes

RANK

RANK() OVER (ORDER BY f DESC) returns the rank position relative to the expression f.

  RANK() OVER (ORDER BY f DESC) 

In this example we show the ranking, by population of those countries with a population of over 180 million.

SELECT name,population,
       RANK() OVER (ORDER BY population DESC)
       AS r
FROM world WHERE population>180000000
ORDER BY name

Using RANK OVER PARTITION

You can see view the RANK according to continent. This shows the biggest country

SELECT
 name,population,
 RANK() OVER (ORDER BY population DESC) AS world_rank,
 RANK() OVER (PARTITION BY continent ORDER BY population DESC) 
            AS local_rank
FROM world WHERE population>100000000
ORDER BY name

See also