我对数据进行了类似的排序,现在我想获得每家公司的前3名最大人员出现率,但我不知道该怎么做。
person_occurence company person_id
67 company_1 110
66 company_2 176
64 company_3 100
64 company_3 196
63 company_4 127
62 company_1 150
61 company_5 120
60 company_3 140
59 company_5 154
59 company_5 162
59 company_4 194
58 company_4 109
58 company_3 128
58 company_1 156
我使用此查询获取每家公司的最多人数,但无法获得前3名最多的person_occurence
SELECT max(agent_occurence), company FROM table GROUP BY company;
答案 0 :(得分:0)
您可以使用 correlated 子查询:
SELECT t1.*
FROM table t1
WHERE t1.person_occurencee = (SELECT max(t2.person_occurence) FROM table t2 WHERE t1.company = t2.company);
如果您的DBMS支持分析功能,那么您也可以:
select t.*
from (select t.*,
rank() over (partition by company order by person_occurrence desc) as seq
from t
) t
where seq <= 3;
答案 1 :(得分:0)
使用窗口功能:
select t.*
from (select t.*,
row_number() over (partition by company order by person_occurrence desc) as seqnum
from t
) t
where seqnum <= 3;
现在,这假定您想要前3个而不考虑平局-也就是说,如果4个具有相同的最高值并发,则返回其中的3个。领带使事情变得更加困难。您可能需要dense_rank()
或rank()
。