7

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

vendor_id、金额和日期。

我想在此表上构建查询到我将获得的位置,按年份分组,按总计(金额总和)排序的前 10 名供应商。

有人能告诉我如何为此使用排名功能。

4

1 回答 1

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
于 2013-08-06T22:43:54.743 回答