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):
| user | amount |
|---|---|
| a | 10 |
| a | 25 |
| a | 7 |
| b | 30 |
| b | 3 |
Output (top 2 per user):
| user | amount |
|---|---|
| a | 25 |
| a | 10 |
| b | 30 |
Runnable example
examples/sql_top_n_per_key.yaml
(manifest name sql-top-n-per-key).
Boundaries
- Per-batch scope, like all
sqlprocessor 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 BYinsideOVER; add a tiebreaker column for deterministic results.