sqladvanced
NTILE and Percentile Window Functions
Distribute rows into buckets and compute percentiles with window functions.
sqlPress ⌘/Ctrl + Shift + C to copy
-- 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.
sqladvanced
Window Frame ROWS vs RANGE Clauses
Control exactly which rows a window function considers using frame specifications.
Best for: Moving averages
#sql#window-frame
sqladvanced
SQL Window Functions for Analytics
Advanced SQL window functions for running totals, rankings, moving averages, and gap analysis.
Best for: Building analytics dashboards with running totals
#sql#window-functions
sqladvanced
SQL Window Functions for Analytics
Use window functions for running totals, rankings, moving averages, and gap detection in analytics.
Best for: Building cumulative revenue dashboards
#sql#window-functions
sqlintermediate
SQL Running Totals and Cumulative Metrics
Calculate running totals, cumulative counts, and percent-of-total using window functions and partitions.
Best for: Building cumulative revenue dashboards
#sql#window-functions