我有一个比赛条目表,里面有很多不同的成员。我想找出迄今为止参加最多比赛的成员。请问我该怎么做?我通过 SQL Developer 使用 Oracle,所以TOP 1
不起作用。
问问题
932 次
5 回答
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
以确保有一个独特的顺序来打破平局。
于 2012-12-10T17:20:00.503 回答
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
于 2012-12-10T17:18:10.740 回答
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;
注意:这只会返回一名成员,即使有几场比赛并列最多。
于 2012-12-10T17:20:24.550 回答
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;
将获得所有参加最多比赛的成员。
于 2012-12-10T17:23:23.610 回答
0
最有效的方法是不使用窗口/分析函数:
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
于 2012-12-10T18:41:36.303 回答