You are on page 1of 1

Variations On a Ranking

The RANK function produces an ordered sequence.


ORDER BY can override the normal sequencing.
Problem
Reverse the ranking sequence in the previous example.
Solution
SELECT storeid
prodid
,sales
,RANK( ) OVER (ORDER BY sales DESC) AS "Ranking"
FROM salestbl
QUALIFY Ranking <= 3
ORDER BY 4 DESC;
Result
storeid prodid sales Ranking
----------- ------ ----------- -----------
1003 B 65000.00 3
1001 A 100000.00 2
1001 F 150000.00 1
Things To Notice:
The ORDER BY clause in the SELECT statement may always be used to control the fi
nal order of the result set.
When the order of sales is DESC, the highest sales amount is always rank #1
After the ranking is applied, the output results are produced based on the ORDER
BY sequence.
The following is an alternate way to produce the same result.
SELECT storeid
,prodid
,sales
,RANK( ) OVER (ORDER BY sales DESC) AS "Ranking"
FROM salestbl
QUALIFY Ranking <= 3
ORDER BY 3 ASC;
Result
storeid prodid sales Ranking
----------- ------ ----------- -----------
1003 B 65000.00 3
1001 A 100000.00 2
1001 F 150000.00 1
Things To Notice:
The ORDER BY clause in the SELECT statement uses the sales column for final orde
ring.

You might also like