sqladvanced

NTILE and Percentile Window Functions

Distribute rows into buckets and compute percentiles with window functions.

sql
-- Divide customers into quartiles by spend
SELECT
  customer_id,
  total_spend,
  NTILE(4) OVER (ORDER BY total_spend DESC) AS spend_quartile
FROM customer_summary;

-- Percentile calculations
SELECT
  department,
  PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary,
  PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY salary) AS p90_salary,
  PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary) AS median_disc
FROM employees
GROUP BY department;

-- PERCENT_RANK and CUME_DIST
SELECT
  employee_id,
  salary,
  PERCENT_RANK() OVER (ORDER BY salary) AS pct_rank,
  CUME_DIST() OVER (ORDER BY salary) AS cumulative_dist
FROM employees;

Use Cases

  • Customer segmentation
  • Salary benchmarking
  • Statistical analysis

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.