2015-06-23 48 views
0

選擇ID我有兩個表發生的最

Users(user_id, name)    

Competition(comp_id, user_id, score) 

,我需要選擇出現在競爭最USER_ID。 我可以用max(count)來做嗎?
如果兩個用戶的發生次數相同,有什麼辦法可以獲得異常嗎?

我想:

SELECT MAX(numberr), USER_ID 
FROM ( 
    SELECT USER_ID, COUNT(COMP_ID) AS numberr 
    FROM COMPETITION 
    GROUP BY USER_ID 
) 
GROUP BY USER_ID; 

但結果我得到的是:

MAX(numberr) USER_ID 
4    1 
2    2 
6    3 

回答

1

你可以把它用做COUNT

SELECT * 
FROM (SELECT USER_ID,COUNT(comp_id) as numberr 
     FROM COMPETITION 
     GROUP BY USER_ID 
     ORDER BY COUNT(comp_id) DESC) T1 
WHERE rownum=1; 
0

你可以用not exists做到這一點。如果有兩個用戶具有相同的最大數量,則會顯示這兩個用戶。

with temp as 
(
    SELECT USER_ID, COUNT(COMP_ID) AS numberr 
    FROM COMPETITION GROUP BY USER_ID 
) 
select * 
from temp t 
where not exists (select 1 from temp where numberr > t.numberr) 

SQLFiddle

0

要獲得多個用戶提供了最大計數使用RANK:

SELECT numberr, USER_ID 
FROM ( 
    SELECT USER_ID, COUNT(COMP_ID) AS numberr 
    ,RANK() OVER (PARTITION BY USER_ID ORDER BY COUNT(COMP_ID) DESC) rnk 
    FROM COMPETITION 
    GROUP BY USER_ID 
) dt 
WHERE rnk = 1;