Memra

NTILE, FIRST_VALUE & frames

◈ 2 cards

Buckets, percentiles, and pulling a value from across the window.

More of the window toolkit

  • ntile(n) — split the ordered rows into n roughly equal buckets (quartiles, deciles…)
  • first_value(expr) / last_value(expr) — the value from the first/last row of the window frame
  • percent_rank(), cume_dist() — relative standing within the partition

The frame controls which rows a window sees. With an ORDER BY, the default frame runs from the start of the partition to the current row — so first_value(salary) OVER (PARTITION BY dept ORDER BY salary DESC) is the top salary in each department.

quartilebooksprice range137.50 – 11.002313.25 – 16.003218.75 – 22.504224.00 – 28.00The remainder lands in the earliest buckets.
ntile(4) OVER (ORDER BY price). Ten rows do not divide by four, so Postgres makes the earliest buckets the larger ones — 3, 3, 2, 2, never a bucket short by more than one.
namedepartmentsalarydept_topBen ChoEngineering185000185000Finn GrayEngineering140000185000Dan EkEngineering120000185000Carla DiazSales175000175000Iris JonesSales110000175000One value pulled from the first row of each partition.
first_value(salary) OVER (PARTITION BY department ORDER BY salary DESC). Every row in a partition looks back to the same first row, so dept_top is constant within a department and changes only when the partition does.
NORMAL ~/memra/learn/postgresql/ntile-and-first-value utf-8 LF