Get the N largest values from a column, with an associated piece of data per value. For example, you can return an accompanying column, or the full row.
max_n_by() functions give the same results as the regular SQL query
SELECT ... ORDER BY ... LIMIT n. But unlike the SQL query, they can be
composed and combined like other aggregate hyperfunctions.
Related hyperfunction groups
- Track the largest values and associated data in a set of values
- Returns the highest values and associated data from a MaxNBy aggregate
- Combine multiple MaxNBy aggregates
Construct an aggregate that keeps track of the largest values passed through it, as well as some associated data which is passed alongside the value.
|The values passed into the aggregate
|The data associated with a particular value
|The number of values to retain.
|The compiled aggregate. Note that the exact type will be MaxByInts, MaxByFloats, or MaxByTimes depending on the input type
This will return the largest values seen by the aggregate and the corresponding values associated with them. Note that PostgresQL requires an input argument with type matching the associated value in order to deterimine the response type.
|The aggregate to return the results from. Note that the exact type here varies based on the type of data stored.
|This is purely to inform PostgresQL of the response type. A NULL cast to the appropriate type is typical.
TABLE (value BIGINT,
TIMESTAMPTZ, data ANYELEMENT)
|The largest values and associated data seen while creating this aggregate.
Find the top 5 values from
i * 13 % 10007 for i = 1 to 10000, and the integer result of the operation that generated that modulus:
This aggregate combines the aggregates generated by other maxnby aggregates and returns the maximum values, with associated data, found across all the aggregated data.
|The aggregates being combined
|An aggregate over all of the contributing values.
This example assumes that you have a table of stock trades in this format:
Find the 10 largest transactions in the table, what time they occurred, and what symbol was being traded:
Found an issue on this page?Report an issue!