SQL(PostgreSQL):如何编写查询来获取前100名最高薪员工的平均工资?

时间:2018-02-16 07:02:19

标签: postgresql

我试图解决的是:

SELECT AVG(amount) FROM (SELECT amount FROM payment ORDER BY amount LIMIT 100);

这也行不通。

SELECT AVG(highest_amount) FROM (SELECT amount AS highest_amount FROM 
payment ORDER BY amount LIMIT 100);

很抱歉提出愚蠢的问题。我是新手。 :(

2 个答案:

答案 0 :(得分:0)

如果您在第一次尝试时给子查询添加别名,它将起作用:

SELECT AVG(amount)
FROM
(
    SELECT amount
    FROM payment
    ORDER BY amount
    LIMIT 100
) t;

如果您想要一种可以在不使用LIMIT的情况下使用的替代方法,那么我们可以尝试使用行号:

SELECT AVG(amount)
FROM
(
    SELECT amount, ROW_NUMBER() OVER (ORDER BY amount) rn
    FROM payment
) t
WHERE rn <= 100;

答案 1 :(得分:0)

解决此类问题的最简单方法是使用 WITH 查询,也称为公用表表达式https://www.postgresql.org/docs/10/static/queries-with.html,结果清晰易懂。

WITH top100 AS 
(
      SELECT 
             amount 
        FROM 
             payment
    ORDER BY 
             amount DESC
       LIMIT 
             100
)
SELECT 
       avg(amout) 
  FROM 
       top100;