使用postgresql返回max,但是如果存在与max的联系,则返回多个值

时间:2018-09-08 04:57:07

标签: postgresql

以下代码的问题是,如果有两个最高薪水,那么每年仍然只返回一个值。我想要这样,如果有多个玩家并列为最大,则将他们全部退还。在PostgreSQL中无法使用TOP ...

SELECT MAX(salaries.pay)
FROM salaries
WHERE salaries.year = 2015 
  OR salaries.year = 2016
GROUP BY salaries.year
LIMIT 1;

1 个答案:

答案 0 :(得分:0)

然后将表连接回salaries

SELECT *
FROM salaries
JOIN (
  SELECT year, MAX(pay)
  FROM salaries
  WHERE year IN ( 2015 , 2016 )
  GROUP BY year
) AS ms
  USING (year, pay);

或者您可以尝试使用dense_rank()

SELECT *
FROM (
  SELECT year, pay, dense_rank() OVER (PARTITION BY year ORDER BY pay) AS dr
  FROM salaries
  WHERE salaries.year IN ( 2015 , 2016 )
) AS ms
WHERE dr = 1;