SQL选择最大聚合

时间:2016-02-06 03:11:20

标签: sql database oracle

我需要选择"工作角色desc"我已达到的最大聚合数。该表如下所示。

[Job Role Description] |  [Number Of Placements]
------------------------------------------------
Training BI                     24
System Analyst                  23
Data Analyst                    24
Data consultant                 25
DB programmer                   24

job_role_desc列来自job_role_id加入的另一个表。我使用以下代码来实现这一目标。

SELECT 
    job_role_dim.job_role_desc AS "Job Role Description" ,
    SUM(fact_accounts.no_of_placements) AS "Number Of Placements" 
FROM 
    fact_accounts 
INNER JOIN 
    job_role_dim ON job_role_dim.job_role_id =  fact_accounts.fk3_job_role_id 
GROUP BY 
    job_role_dim.job_role_desc

如何修改上述代码,才能显示具有最多展示位置的job_role_desc?谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

您可以使用row_number()dense_rank()

SELECT ja.*
FROM (SELECT j.job_role_desc AS "Job Role Description" ,   
             SUM(a.no_of_placements) AS "Number Of Placements",
             ROW_NUMBER() OVER (ORDER BY SUM(a.no_of_placements) DESC) as seqnum
      FROM fact_accounts a INNER JOIN
           job_role_dim j
           ON j.job_role_id = a.fk3_job_role_id
      GROUP BY j.job_role_desc
     ) ja
WHERE seqnum = 1;

如果您希望所有版本都达到最大值,请使用dense_rank()rank()