132 High-Function Business Intelligence in e-business
The result of this query is shown in Figure 3-11.
Figure 3-11 RANK, DENSE_RANK and ROW_NUMBER comparison
RANK and PARTITION BY example
The following is an example of using the PARTITION BY clause which allows for
subdividing the rows into partitions. It functions similar to the GROUP BY
function, but is local to the window set whereas GROUP BY is a global function.
Assume we want to find the top 4 ranking of employee salary within each
department.
We will need to use the RANK function with partition (ranking window) by
department. We will need to use a common table expression otherwise the
reference to RANK_IN_DEPT in our subselect is ambiguous.
The SQL is shown in Example 3-18.
Example 3-18 RANK & PARTITION example
WITH SALARYBYDEPT AS(
SELECT WORKDEPT, LASTNAME, FIRSTNME,SALARY,
RANK() OVER (PARTITION BY WORKDEPT ORDER BY SALARY DESC NULLS LAST)
AS RANK_IN_DEPT
FROM EMPLOYEE )
SELECT WORKDEPT, LASTNAME,FIRSTNME,SALARY, RANK_IN_DEPT
FROM SALARYBYDEPT
WHERE RANK_IN_DEPT <= 4 AND WORKDEPT IN
('A00','A11','B01','C01','D1','D11')
ORDER BY WORKDEPT, RANK_IN_DEPT, LASTNAME