Return 查询结果中前 5 个值的平均值

Return the AVG of the Top 5 Values in Query Results

问题:我如何return下面支付排名查询中前 5 个值的 AVG。

数据库:Oracle 11g

当前查询

select distinct pye.payeeid, pay.value,
dense_rank() over (partition by bu.name order by pay.value DESC) as "Payment Ranking"

from cs_period per, cs_payee pye, cs_payment pay, cs_businessunit bu

where per.name = 'August 2014'
and pye.payeeseq = pay.payeeseq
and pay.businessunitmap = bu.mask
and pye.effectiveenddate = to_date('01/01/2200','dd/mm/yyyy')
and pye.removedate = to_date('01/01/2200','dd/mm/yyyy')
and per.periodseq = pay.periodseq
order by pay.value DESC

结果

select avg(payment)
from
(
    <your query here>
)
where rownum <= 5

假设您保持查询中显示的顺序。

我假设你想要根据 "Payment Ranking" 的前 5 名(你使用 DENSE_RANK() 而不是 RANK()ROW_NUMBER()):

SELECT AVG(value) FROM (
    select distinct pye.payeeid, pay.value
         , dense_rank() over (partition by bu.name order by pay.value DESC) as payment_ranking
     from cs_period per, cs_payee pye, cs_payment pay, cs_businessunit bu
    where per.name = 'August 2014'
      and pye.payeeseq = pay.payeeseq
      and pay.businessunitmap = bu.mask
      and pye.effectiveenddate = to_date('01/01/2200','dd/mm/yyyy')
      and pye.removedate = to_date('01/01/2200','dd/mm/yyyy')
      and per.periodseq = pay.periodseq
) WHERE payment_ranking <= 5

请注意,我所做的只是接受您的查询并将其用作子查询,添加 WHERE 子句以限制排名前 5 位的付款。