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

4

3 回答 3

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

于 2012-11-18T23:03:42.980 回答
1

试试这个: SQLFiddle 演示

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
于 2012-11-18T23:05:08.393 回答
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)

请注意,如果他们都具有相同的命中数,这将返回多个玩家。还要注意,如果一名球员出现在分数表中但不在球员表中,它将不会显示。

于 2012-11-18T23:41:21.070 回答