寻找最频繁命中的人

时间:2012-11-18 22:59:12

标签: sql oracle sqlplus

我是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,因为他在所有其他玩家中的命中率最高。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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)

请注意,如果所有玩家的点击次数相同,则会返回多个玩家。另请注意,如果玩家出现在得分表中但不在玩家表中,则不会显示。