2013-09-27 57 views
1

以下查詢返回擁有最多朋友的用戶。視圖allUserFriendCounts列出了他們有多少朋友旁邊的所有用戶名(爲了我的問題,我需要使用此視圖)。運行下面的查詢似乎需要運行allUserFriendCounts的兩倍,因爲它必須運行後者兩次。在不調用視圖兩次的情況下獲取最大值

有沒有一種方法可以更有效地重寫?

create or replace view getMaxFriendCount(name) as 
    select f.name 
    from allUserFriendCounts f 
    where f.friendcount = (select max(committeecount) from allUserFriendCounts) 
    GROUP BY name 
; 

我使用PostgreSQL 9.2.1

+0

這一直是最有效的 – sunysen

+0

你有一個類型在您的查詢,我是嗎? 'userFriendCounts'應該是'allUserFriendCounts'? –

+0

@RomanPekar你是對的 - 現在改變 – warchinal

回答

1

如果我理解你,你的初始查詢是:

select f.name 
from allUserFriendCounts f 
where f.friendcount = (select max(c.friendcount) from allUserFriendCounts as c) 
group by name 

所以你可以使用dense_rank()rank()您所查詢:

with cte as (
    select 
     *, 
     rank() over(order by f.friendcount desc) as rnk 
    from allUserFriendCounts as f 
) 
select name 
from cte 
where rnk = 1 

sql fiddle demo

+0

這確實是效率的兩倍!謝謝! – warchinal

相關問題