简体   繁体   English

如何在GROUP BY的行中添加数字列的列?

[英]How can I add a column with numeric rank to the rows within a GROUP BY?

Given the table of employee data below: 给定以下员工数据表:

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

Please help with a query to output the listing below, sequencing salary in descending order within each department where the highest salary is assigned sequence #1: 请帮助查询以输出以下列表,在分配最高薪水的每个部门中按降序对薪水进行排序:#1:

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

Thanks! 谢谢!

You can use analytical functions for this, specifically the RANK() function: 您可以为此使用分析函数,特别是RANK()函数:

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

The PARTITION performs the ranking by department; PARTITION按部门执行排名; remove it and you'll get a ranking across all departments. 删除它,您将获得所有部门的排名。

The RANK will include ties, so if there are two people who share the highest salary in the department they'll both rank #1, and the next-highest salary will rank #3. RANK将包含联系,因此,如果有两个人在该部门中拥有最高的薪水,则他们都将排在第一位,而第二高的薪水将排在第三位。 If you want the next-highest salary to rank #2 instead of #3, use DENSE_RANK. 如果您希望第二高的薪水排名第二,而不是第三,请使用DENSE_RANK。

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

Ooops, WITHIN GROUP cant be used as an analytical,here is an alternative 糟糕,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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM