Using postgres ranking function to limit n top results

I am requesting a payable table, in which there is a list of ap documents of which everyone has (among other fields) those that interest me, to run aggregated queries:

vendor_id, quantity and date.

I would like to build a query on this table, wherever I would receive, grouped by year, the top 10 sellers sorted by sum (sum of sums).

Someone please tell me how to use the rank function for this.

+6
source share
1 answer
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 
+7
source

Source: https://habr.com/ru/post/951164/


All Articles