Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RANKing in group by in oracle

Tags:

sql

oracle

I have a query

Select age,qualification,sum(income) as total_income  from employee
group by age,qualification;

I want to find rank on based total_income for the group of age and qualification.

For example

19|Grad|5000|rank:1
19|Grad|4000|rank:2
19|Grad|3000|rank:3
26|Grad|6000|rank:1
26|Grad|5000|rank:2
26|PosG|8000|rank:1
26|PosG|6000|rank:2

Can I do it in Oracle? I tried with partition by but not able to figure it out.

like image 377
Neo Avatar asked Mar 15 '23 07:03

Neo


1 Answers

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE Employees ( Age, Qualification, Income ) AS
          SELECT 19, 'Grad', 5000 FROM DUAL
UNION ALL SELECT 19, 'Grad', 4000 FROM DUAL
UNION ALL SELECT 19, 'Grad', 3000 FROM DUAL
UNION ALL SELECT 26, 'Grad', 6000 FROM DUAL
UNION ALL SELECT 26, 'Grad', 5000 FROM DUAL
UNION ALL SELECT 26, 'PosG', 8000 FROM DUAL
UNION ALL SELECT 26, 'PosG', 6000 FROM DUAL;

Query 1:

SELECT Age,
       Qualification,
       Income,
       RANK() OVER ( PARTITION BY Age, Qualification ORDER BY Income DESC ) AS "Rank"
FROM   Employees

Results:

| AGE | QUALIFICATION | INCOME | Rank |
|-----|---------------|--------|------|
|  19 |          Grad |   5000 |    1 |
|  19 |          Grad |   4000 |    2 |
|  19 |          Grad |   3000 |    3 |
|  26 |          Grad |   6000 |    1 |
|  26 |          Grad |   5000 |    2 |
|  26 |          PosG |   8000 |    1 |
|  26 |          PosG |   6000 |    2 |

Query 2:

WITH total_incomes AS (
  SELECT Age,
         Qualification,
         SUM( Income ) AS total_income
  FROM   Employees
  GROUP BY
         Age,
         Qualification
)
SELECT Age,
       Qualification,
       total_income,
       RANK() OVER ( ORDER BY total_income DESC ) AS "Rank"
FROM   total_incomes

Results:

| AGE | QUALIFICATION | TOTAL_INCOME | Rank |
|-----|---------------|--------------|------|
|  26 |          PosG |        14000 |    1 |
|  19 |          Grad |        12000 |    2 |
|  26 |          Grad |        11000 |    3 |
like image 67
MT0 Avatar answered Mar 23 '23 13:03

MT0