如何在GROUP BY中的行中添加具有数字排名的列?

时间:2015-02-04 17:19:25

标签: sql oracle

根据以下员工数据表:

Employee_id Employee_department Salary
100         ACCOUNTING          50000
200         SALES               75000
300         SALES               100000
400         ACCOUNTING          60000

请帮助查询输出下面的列表,在每个部门中按降序排序工资,其中最高工资分配顺序#1:

Employee_id Employee_department Salary Sequence
400         ACCOUNTING          60000  1
100         ACCOUNTING          50000  2
300         SALES               100000 1
200         SALES               75000  2

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用分析函数,特别是RANK()函数:

SELECT
  Employee_id,
  Employee_department,
  Salary,
  RANK() OVER (PARTITION BY Employee_department ORDER BY Salary DESC) AS Sequence
FROM myTable

PARTITION按部门执行排名;删除它,你将获得所有部门的排名。

RANK将包括关系,所以如果有两个人在部门中分享最高薪水,他们都会排名第一,而次高薪将排在第3位。如果您希望下一个最高薪水排名#2而不是#3,请使用DENSE_RANK。

答案 1 :(得分:1)

SELECT Employee_id, Employee_department, Salary,
RANK() WITHIN GROUP
   (ORDER BY Employee_department ASC, Salary DESC) "Sequence" 
FROM t

糟糕,WITHIN GROUP不能用作分析,这里是另类

SELECT Employee_id, Employee_department, Salary,
(SELECT COUNT(*)
          FROM t x 
         WHERE x.salary >= t.salary AND x.Employee_department =t.Employee_department ) AS  "Sequence"
FROM t
ORDER BY Employee_department ASC, Salary DESC