2012-11-18 80 views
2

我是SQL新手,想學習它。發生在我身上的一個問題是如何找到表中某個人的特定事件的最大數量。我不確定查詢如何將每個ID與另一個ID進行比較並跟蹤計數。可憐的解釋,但這裏有一個數據集,希望更清楚。找到最頻繁點擊的人

players: 
+--------+--------+ 
| pid | name | 
+--------+--------+ 
| 1  | Tom | 
| 2  | Sam | 
| 3  | Dan | 
+--------+--------+ 

scores: 
+--------+--------+--------+ 
| sid | pid | result | 
+--------+--------+--------+ 
| 1  | 1  | miss | 
| 2  | 1  | hit | 
| 3  | 3  | hit | 
| 4  | 2  | miss | 
| 5  | 3  | hit | 
| 6  | 3  | hit | 
+--------+--------+--------+ 

預期的答案是pid = 3,name = Dan,因爲他的所有其他玩家的命中率最高。

回答

2
Select 
    p.pid, 
    p.name 
From (
    Select 
    p.pid, 
    p.name, 
    count(*) 
    From 
    players p 
     inner join 
    scores s On 
     p.pid = s.pid 
    Where 
    result = 'hit' 
    Group By 
    p.pid, 
    p.name 
    Order By 
    count(*) Desc 
) p 
Where 
    rownum = 1; 

http://sqlfiddle.com/#!4/03ba0/22

+0

sqlfiddle給出1的結果,湯姆。應該是3,丹。 – user1834372

+0

@ user1834372糟糕,忘記了Oracle在訂單前應用rownum,現在已經修復。 – Laurence

1

試試這個:SQLFiddle Demo

select pid, hits from(
    Select p.pid, count(*) as hits FROM players p 
    JOIN scores s 
     ON p.pid = s.pid AND s.result = 'hit' 
    GROUP BY p.pid 
    ORDER By count(*) DESC 
) 
Where rownum <= 1 
+0

謝謝你。現在我會去了解所有關於連接的知識。 – user1834372

0

這也可能是一個解決辦法:

select 
    players.pid, 
    players.name 
from 
    scores inner join players 
    on scores.pid = players.pid 
    and scores.result = 'hit' 
group by players.pid, players.name 
having count(*)=(select max(cnt) 
       from 
        (select pid, count(*) as cnt 
        from scores 
        where result='hit' 
        group by pid) t) 

請注意,這會返回一個以上的球員,如果他們都相同數量的點擊。另外請注意,如果玩家出現在得分表中,但不出現在玩家表中,則不會顯示。