如何使用sql计算表中最常见的条目?

时间:2012-12-10 17:05:39

标签: sql oracle count

我有一个包含不同成员的竞赛入围表。我想找出目前为止参加比赛最多的成员。我该怎么做呢?我通过SQL Developer使用Oracle,因此TOP 1不起作用。

5 个答案:

答案 0 :(得分:2)

最有效的方法通常是使用分析函数

SELECT member_no,
       cnt
  FROM (SELECT member_no, 
               count(*) cnt,
               rank() over (order by count(*) desc) rnk
          FROM race
         GROUP BY member_no)
 WHERE rnk = 1

您还可以执行GROUP BY/ HAVING查询,但这会涉及两次点击race表,这通常效率较低。

如果出现平局,你想要发生什么?如上所述,如果有多个member_no值与race表中的大多数条目相关联,则我发布的查询将返回多行。如果您想随意选择一个member_no值,则可以使用row_number分析函数而不是rank。或者您可以为order by子句添加一些额外的条件,以确保有一个独特的顺序来打破平局。

答案 1 :(得分:1)

您应该能够应用count()汇总和group by member_no来获得总数:

select member_no, count(*) TotalEntries
from yourtable
group by member_no 
order by TotalEntries desc

然后,如果你想限制你应该能够使用的记录:

select member_no, TotalEntries
from
(
    select member_no, count(*) TotalEntries, row_number() over(order by count(*) desc) rn
    from yourtable
    group by member_no 
) src
where rn = 1

答案 2 :(得分:0)

尝试这样的事情:

with
data as (
    -- Create some test data
    select distinct mod(rownum,20)+1 race_id, round(DBMS_RANDOM.VALUE(1,5)) member_id 
    from dual
    connect by level <= 100
)
-- real query starts here
select *
from (
    select member_id, count(*) race_count
    from data
    group by member_id
    order by race_count desc
)
where rownum <= 1;

注意:这只会返回一个成员,即使大多数比赛都有几个并列。

答案 3 :(得分:0)

select member_id, races
  from (select member_id, count(*) races, rank() over (order by count(*) desc) rnk
          from your_table
         group by member_id)
 where rnk = 1;

将获得所有参加过最多比赛的成员。

答案 4 :(得分:0)

执行此操作的最有效方法是不使用Windows /分析函数:

select member_no, TotalEntries
from (select member_no, count(*) TotalEntries, rownum as seqnum
      from yourtable
      group by member_no 
      order by 2 desc
     ) t
where seqnum = 1