Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using postgres rank function to limit to n top results

I am querying an account payables table that has list of ap documents of which each has ( among other fields) the ones I am interested in to run aggregate queries over:

vendor_id, amount and a date.

I would like to construct the query over this table to where I would be getting, grouped by year, top 10 vendors ordered by total (sum of amounts).

Would someone tell me please how to use rank function for this.

like image 297
Edmon Avatar asked Aug 06 '13 20:08

Edmon


People also ask

How do I limit rows in PostgreSQL?

The LIMIT clause can be used with the OFFSET clause to skip a specific number of rows before returning the query for the LIMIT clause. Syntax:SELECT * FROM table LIMIT n OFFSET m; Let's analyze the syntax above. The LIMIT clause returns a subset of “n” rows from the query result.

How do I create a rank function in PostgreSQL?

In PostgreSQL, the RANK() function is used to assign a rank to each row of the query result set within the specified partition. The rank of the first row within each partition is 1. The following illustrates the syntax of the RANK() function: Syntax: RANK() OVER ( [PARTITION BY partition_expression, ... ]

What is difference between rank and Dense_rank?

rank and dense_rank are similar to row_number , but when there are ties, they will give the same value to the tied values. rank will keep the ranking, so the numbering may go 1, 2, 2, 4 etc, whereas dense_rank will never give any gaps.

Does PostgreSQL have limit?

PostgreSQL does not impose a limit on the total size of a database. Databases of 4 terabytes (TB) are reported to exist. A database of this size is more than sufficient for all but the most demanding applications.


1 Answers

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
like image 196
Clodoaldo Neto Avatar answered Dec 11 '22 03:12

Clodoaldo Neto