【问题标题】:Fetch the row which has the second max value in a column from a table postgres从表 postgres 中获取列中具有第二个最大值的行
【发布时间】:2014-12-17 09:03:30
【问题描述】:

我的桌子是

 emp_id | emp_name |  emp_doj   |    emp_desg     |  pay   | manager_id
--------+----------+------------+-----------------+--------+------------
      3 | John     | 2008-12-20 | MTS             |  93750 |          3
      5 | manoj    | 2014-08-10 | Project Trainee | 200000 |          3
      6 | kumar    | 2014-09-12 | Project Trainee |  15000 |          3
      2 | Sree     | 2014-09-12 | ZU              | 150000 |          3

我想从这张表中获取完整的行,哪一行的薪水第二高。也就是说,我想在这里获取sree的详细信息....

【问题讨论】:

    标签: sql postgresql max greatest-n-per-group


    【解决方案1】:

    试试这个:

    select max(pay) from table_name where pay NOT IN(select max(pay) from table_name) LIMIT 0,1
    

    这对你有帮助。

    【讨论】:

    • 其实我想得到整行...当我这样做时会出错
    • 应该指定像 select emp_id, emp_name,emp_doj,emp_desg,emp_manager_id,max(pay) as pay from table_name where pay NOT IN(select max(pay) from table_name)
    【解决方案2】:

    这可以使用窗口函数轻松完成:

    select emp_id, emp_name, emp_doj, emp_desg, pay, manager_id
    from (
      select emp_id, emp_name, emp_doj, emp_desg, pay, manager_id,
             dense_rank() over (order by pay desc) as rnk
      from employee
    ) t
    where rnk = 2;
    

    如果两名员工的工资相同,则两者都将被退回。如果您只想返回其中一个,请使用row_number() 而不是dense_rank()

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 2019-12-21
      • 2022-09-29
      • 2011-11-27
      • 2017-09-20
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多