使用postgres排名功能限制n个顶级结果

Edm*_*mon 6 sql postgresql greatest-n-per-group window-functions

我正在查询一个应付帐款表,其中包含ap文档列表,其中每个文档都包含我感兴趣的(以及其他字段)运行聚合查询的文件:

vendor_id,金额和日期.

我想在这个表上构建查询到我将获得的位置,按年份排序,前10名供应商按总数(金额总和)排序.

有人会告诉我如何使用排名功能.

Clo*_*eto 7

select *
from (
    select the_year, vendor_id, amount,
        row_number() over(
            partition by the_year
            order by amount desc
        ) as rn
    from (
        select
            date_trunc('year', the_date) as the_year,
            vendor_id,
            sum(amount) as amount
        from ap
        group by 1, 2
    ) s
) s
where rn <= 10
order by the_year, amount desc
Run Code Online (Sandbox Code Playgroud)