带有两个表的Oracle SQL STATS_MODE

时间:2017-11-19 04:44:42

标签: sql oracle

我有图片中列出的表格。我需要在sale_financing表中显示最常用融资计划的机构和贷款类型。我已经尝试过使用stats_mode函数但是我无法让它工作。我应该只显示最常用的融资计划,我不断出现3。这是表格的图像。

enter image description here

我的图片可能无效,所以这里是表格:

financing_plan
     id
     institution
     loan_type

sale_financings
     id
     plan_id ------> foreign key linking to - financing_plan.id

我在查询生成器中尝试了几种不同的方法,但我无法使其工作。

这是一个:

SELECT
    financing_plans.institution,
    financing_plans.loan_type,
    STATS_MODE(sale_financings.plan_id) AS stats_mode_plan_id
FROM
    financing_plans
    INNER JOIN sale_financings ON financing_plans.id = 
    sale_financings.plan_id
GROUP BY
    financing_plans.institution,
    financing_plans.loan_type

另:

SELECT
    financing_plans.institution,
    financing_plans.loan_type,
    STATS_MODE(sale_financings.plan_id) AS stats_mode_plan_id
FROM
    financing_plans
    INNER JOIN sale_financings ON financing_plans.id = 
    sale_financings.plan_id
GROUP BY
    financing_plans.institution,
    financing_plans.loan_type
HAVING
    STATS_MODE(sale_financings.plan_id) = sale_financings.plan_id

1 个答案:

答案 0 :(得分:1)

计算每个plan_id的使用情况,然后按计数(降序)对这些(使用dense_rank())进行排名,允许" top"并且"等于顶部"显示。

select
      fp.institution, fp.loan_type, s.plan_count
from financing_plan fp
inner join (
      select plan_id, plan_count, dense_rank() over(order by plan_count DESC) as rnk
      from (
            select plan_id, count(id) plan_count
            from sale_financings
            Group by plan_id
           )
      ) s on fp.id = s.plan_id and s.rnk = 1
order by 
      fp.institution, fp.loan_type
;