我有一个名为employees的表,其中'employee_id'
和'bonuses'
为列。重复 employee_id ,因为他们有多个不同金额的奖金,我想按总奖金额对其进行排名。
所以,我想知道这是否是按照总奖金额下降对员工进行排名的正确方法:
SELECT employee_id, SUM(bonuses) AS total_bonus, DENSE_RANK(ORDER BY total_bonus DESC) AS bonus_rank
FROM employees
GROUP BY employee_id;
我想要的输出是只列出一次employee_id
的表格,相应的total bonus amount the employee received
和rank of bonuses starting from rank #1 with the highest total bonus amount
。
答案 0 :(得分:0)
您可以在ORDER BY子句中使用计算的Bonus值 - 无需担心密集排名。
SELECT employee_id, SUM(bonuses) AS total_bonus
FROM employees
GROUP BY employee_id
ORDER BY SUM(bonuses) DESC
答案 1 :(得分:0)
我发现您的查询没有任何问题,只是您尝试在total_bonus
功能的DENSE_RANK()
功能中使用别名SELECT
。这是不可能做到的,AFAIK,因为别名尚不可用。相反,只需再次使用SUM()
术语:
SELECT employee_id,
SUM(bonuses) AS total_bonus,
DENSE_RANK(ORDER BY SUM(bonuses) DESC) AS bonus_rank
FROM employees
GROUP BY employee_id;