2014-11-21 60 views
1

确定在 派对中任职期限最长的总统的姓名,派对和年份。我无法使用join关键字。寻找行组的最大值POSTGRESQL

表总裁:

Name        | Party     | years_served| 
-------------+-------------+-------------+ 
Roosevelt  | Democratic | 12 
Madison   | Demo-rep   | 8 
Monroe    | Demo-rep   | 8 
Adams     | Demo-rep   | 4 

那么结果将是罗斯福,麦迪逊和门罗出现了,亚当斯并没有因为他没有满足8年这是最大的演示代表。

回答

0

试试这个:

SELECT Name 
FROM President pr 
    INNER JOIN (SELECT Party, MAX(years_served) as YS FROM president GROUP BY Party) as MaxYS on MaxYS.Party=Pr.Party 
WHERE pr.years_served>=MaxYS.YS 

希望是你在找什么。

+0

我不能在这里使用join关键字 – wickys 2014-11-21 12:37:22

+0

@wickys:为什么你认为你不能使用连接那里? – 2014-11-21 12:38:43

+0

我可以问为什么你不能? – ericpap 2014-11-21 12:38:54

1

可以使用dense_rank()窗函数:

with cte as (
    select 
     *, dense_rank() over(partition by Party order by years_served desc) as rnk 
    from Table1 
) 
select 
    Name, Party, years_served 
from cte 
where rnk = 1 

sql fiddle demo