指定限制的SQL最大值

时间:2019-03-04 07:54:49

标签: sql database postgresql max

我试图返回满足某些条件的年份列表,但是我在使用MAX函数时遇到麻烦,并且无法使其与我的其余逻辑一起使用。

对于以下两个表:

          coach
coach | team | wins | year
------+------+------+------
nk01  | a    | 4    | 2000
vx92  | b    | 1    | 2000
nk01  | b    | 5    | 2003
vx92  | a    | 2    | 2003

           team
team | worldcupwin | year
-----+-------------+------
a    | Y           | 2000
b    | N           | 2000
a    | Y           | 2003
b    | N           | 2003

我想得到以下输出:

years
-----
2000

印有年份的年份是那年中获胜最多的教练团队也获得世界杯冠军的地方。

我决定使用MAX函数,但是很快就遇到了一个问题,就是不知道如何使用它,而只是寻找特定年份的最大值。这是到目前为止我得到的:

SELECT y.year
FROM (SELECT c.year, MAX(c.wins), c.team
      FROM coach AS c
      WHERE c.year >= 1999
      GROUP BY c.year, c.team) AS y, teams AS t
WHERE y.year = t.year AND t.worldcupwin = 'Y' AND y.team = t.team;

对于我来说,此查询输出的年份大于1999年,而不仅仅是那些获胜最多的教练也获得了世界杯冠军的年份。 (使用postgresql)

感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

您可以使用相关子查询

DEMO

   SELECT c.year, c.team
      FROM coachs AS c inner join teams t on c.team = t.team and c.year=t.year
      WHERE c.year >= 1999 and exists (select 1 from coachs c1 where c.team=c1.team 
      having max(c1.wins)=c.wins) 

and t.worldcupwin ='Y'

输出:

year    team
2000    a 

答案 1 :(得分:1)

以下查询使用DISTINCT ON

SELECT DISTINCT ON (year) c.year, wins, worldcupwin, c.team
FROM coach AS c
INNER JOIN team AS t ON c.team = t.team AND c.year = t.year 
WHERE c.year > 1999 
ORDER BY year, wins DESC

为了返回每年获胜次数最多的记录

year    wins    worldcupwin team
---------------------------------
2000    4       Y           a
2003    5       N           b

过滤掉没有赢得世界杯的球队:

SELECT year, team
FROM (
   SELECT DISTINCT ON (year) c.year, wins, worldcupwin, c.team
   FROM coach AS c
   INNER JOIN team AS t ON c.team = t.team AND c.year = t.year 
   WHERE c.year > 1999 
   ORDER BY year, wins DESC) AS t
WHERE t.worldcupwin = 'Y'       
ORDER BY year, wins DESC

达到预期结果:

year    team
-------------
2000    a

Demo here

答案 2 :(得分:1)

您可以使用下面的方法获得所需的结果:

  

简便方法

SELECT TOP 1 c.year 

FROM coach AS c INNER JOIN team AS t ON c.team = t.team AND c.year = t.year

WHERE t.worldcupwin = 'Y'

ORDER BY c.wins DESC;

答案 3 :(得分:0)

使用row_number()窗口功能

select a.coach,a.team,a.win,a.year from 

 (select c.*,t.*,
row_number()over(order by wins desc) rn 
from  coach c join team t on c.team=t.team
 where worldcupwin='Y'
 ) a where a.rn=1