sql - 使用 Partition by 的 SQL 中最高和第五高薪水之间的差异

标签 sql postgresql window-functions

我有这样的数据:

CREATE TABLE salaries AS
SELECT * FROM ( VALUES
  ('US'    , 'A', 3935),
  ('US'    , 'B', 7805),
  ('US'    , 'C', 2302),
  ('US'    , 'D', 6772),
  ('US'    , 'E', 3173),
  ('US'    , 'F', 7739),
  ('Japan' , 'G', 3881),
  ('Japan' , 'H', 1158),
  ('Japan' , 'I', 2591),
  ('Japan' , 'J', 3758),
  ('Japan' , 'K', 8710),
  ('Japan' , 'L', 3376),
  ('France', 'M', 5768),
  ('France', 'N', 9466),
  ('France', 'O', 1750),
  ('France', 'P', 1049),
  ('France', 'Q', 3479),
  ('France', 'R', 5305)
) AS t(country,employee,salary);

为了找出每个国家最高薪水和第五高薪水之间的差异,我正在尝试以下方法:

select max(salary) over (partition by country) - rank(5) over (partition by country) 
from salaries

但它抛出以下错误:

“有序集合聚合函数需要 WITHIN GROUP”

任何人都可以在不使用任何连接的情况下提出任何方法吗?

最佳答案

select      country
           ,max(salary) - max(case dr when 5 then salary end) as salary_diff

from       (select      country     
                       ,salary
                       ,dense_rank() over (partition by country order by salary desc) as dr

            from        salaries
            ) s

group by    country            

关于sql - 使用 Partition by 的 SQL 中最高和第五高薪水之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41249134/

相关文章:

mysql - Like Statement 在 sequelize 中对我不起作用

sql - Node JS Express - Oracle 连接池 (ORA-24418 : Cannot open further sessions)

ruby-on-rails - JSON 数据在开发中正确显示,但在生产中显示不正确

sql - 为列的每个唯一值选择 X 个最新行

sql - PostgreSQL 窗口函数排序

mysql - 如何在 SQL 中执行迭代

sql - 仅返回该值出现超过 n 次的行

django - 如何根据3个表找到需要操作的id?

sql - 如何更好的优化SQL查询?

sql - 删除所有行,但每组中值最大的行除外