【问题标题】:Using postgres rank function to limit to n top results使用 postgres rank 函数限制到 n 个顶级结果
【发布时间】:2013-08-08 01:21:01
【问题描述】:

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

vendor_id、金额和日期。

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

有人能告诉我如何使用排名功能吗?

【问题讨论】:

标签: sql postgresql greatest-n-per-group window-functions


【解决方案1】:
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

【讨论】:

  • 太棒了!我做了一个小编辑,因为在分区后有一个昏迷,但其他方面非常好。运行快速准确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 2017-10-13
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多