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

Difference between highest and fifth highest salaries in SQL using Partition by

我有这样的数据:

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 is required for ordered-set aggregate function"

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

select country, max_sal - salary
from (
     select country, salary, 
            max(salary) over (partition by country) max_sal,
           case when (row_number() over (partition by country
                                         order by salary desc)) = 5 
                then 1 
           end fifth
from table
) t where fifth is not null;
  1. 创建一个 WINDOW 定义您想要的(按国家/地区划分,按薪水降序排列)
  2. 计算 max(salary) window
  3. 从顶部计算 nth_value(因为它们是按薪水降序排列的)

需要特别注意的是 WINDOWS 有范围和行。他们详细说明了如何在 window 中执行计算。在这里,我们必须取消绑定 WINDOW 才能让 nth_value() 工作。通常,它会根据看到的所有内容进行计算,因此 nth_value 只有在看到该行时才会启动——但我们可以让它看到前方。

代码,

SELECT *
  , max(salary) OVER w1 - nth_value(salary,5) OVER w1 AS max_minus_fifth_highest
FROM foo
WINDOW w1 AS (
  PARTITION BY (country)
  ORDER BY SALARY desc
  ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
)
ORDER BY country;

Sql Demo

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 DEMO

with fifth as (
     SELECT country, "salary",
            rank() over (partition by "country" order by "salary" desc)  rnk
     FROM salaries
)
SELECT *
FROM salaries s
JOIN fifth f
  ON s.country = f.country
 AND f.rnk = 5

输出