Skip to main content
Version: 0.7.x

Top-N per key

Pattern. Keep the N largest (or smallest) rows per key inside the batch — "a user's two biggest orders", "the three slowest endpoints per region".

The query​

SELECT user, amount
FROM (
SELECT user, amount,
row_number() OVER (PARTITION BY user ORDER BY amount DESC) AS rn
FROM flow
) ranked
WHERE rn <= 2

Swap DESC for ASC for bottom-N, or replace row_number() with rank() / dense_rank() when ties should share a rank (N then applies to rank values, possibly returning more than N rows per key).

Input and output​

Input (five rows):

useramount
a10
a25
a7
b30
b3

Output (top 2 per user):

useramount
a25
a10
b30

Runnable example​

examples/sql_top_n_per_key.yaml (manifest name sql-top-n-per-key).

Boundaries​

  • Per-batch scope, like all sql processor queries. For a continuous top-N across batches, aggregate into windows with a Job (see windowed aggregation recipe) and apply this pattern on the window output.
  • Tie handling and stable output order come from the ORDER BY inside OVER; add a tiebreaker column for deterministic results.