【问题标题】:SQL query using limit while considering duplicates考虑重复时使用限制的 SQL 查询
【发布时间】:2017-03-29 01:15:20
【问题描述】:

我正在使用查询来使用限制从表中获取前 3 条记录,如下所示:

select name, salary 
from employees 
order by salary desc
limit 3;

问题是可能有工资相同的员工,在这种情况下我不希望我的限制是 3

----------------------------
|    name    |    salary   |
----------------------------
|   Robert   |    10000    |
|     Jon    |    20000    |
| Alexander  |    30000    |
|    James   |    20000    |
|    Mike    |    40000    |
----------------------------

所以在本例中,我希望限制为 4,因为有两名员工的薪水为 20000。有没有办法在不事先知道会有多少人的情况下考虑重复项?

【问题讨论】:

    标签: sql database limit querying


    【解决方案1】:

    您需要先确定要包括的工资范围。

    select name, salary 
      from employees 
     where salary in ( select distinct salary 
                    from employees
                    order by salary desc
                    limit 3 )
     order by salary DESC ;
    

    【讨论】:

    • 谢谢,这正是我需要的!
    猜你喜欢
    • 2021-02-22
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 2023-01-15
    相关资源
    最近更新 更多