首页 > 解决方案 > 如何获得比当前元组有更好薪水的人数

问题描述

我正在解决 Leetcode #185中的一个问题

我可以理解该解决方案,但我想知道如何编写查询以添加一列,该列指示人们的薪水比元组高的人数。我认为这在 SQL 中是可能的,但我不知道如何使它正确,我总是得到语法错误。:-/

from Employee e1 (Select count(distinct e2.Salary)
                  from Employee e2
                  Where e2.Salary > e1.Salary) as c

例如,我有这样一个表 Employee:

Id - Name - Salary
1    toto   60000
2    tata   50000
3    kiki   90000
4    lily   70000
5    momo   60000

我想要这样的结果:

Id - Name - Salary - Head_count_of_higher_salary
1    toto   60000      2
2    tata   50000      4
3    kiki   90000      0
4    lily   70000      1
5    momo   60000      2

多谢你们

标签: mysqlsqlgroup-bycountwindow-functions

解决方案


If you are running MySQL 8.0: what you ask for is exactly what rank() does.

This would be as simple as:

select e.*, rank() over(order by salary desc) - 1 head_count_of_higher_salary
from employees e

推荐阅读