SQL Window Functions: Percentiles, Bucketing, and Distribution Analysis
Percent rank, cumulative distribution, percentile-style bucketing, and segmentation patterns.
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Distribution functions
## Segmentation patterns
WITH bucketed AS (
SELECT customer_id,
lifetime_value,
NTILE(4) OVER (ORDER BY lifetime_value DESC) AS quartile
FROM customers
)
SELECT customer_id,
lifetime_value,
CASE WHEN quartile = 1 THEN 'top_quartile' ELSE 'other' END AS segment
FROM bucketed;# Turn NTILE output into a simple segment label.
WITH scored AS (
SELECT user_id,
engagement_score,
NTILE(5) OVER (ORDER BY engagement_score DESC) AS bucket
FROM user_scores
)
SELECT user_id,
engagement_score,
CASE bucket
WHEN 1 THEN 'elite'
WHEN 2 THEN 'high'
WHEN 3 THEN 'medium'
WHEN 4 THEN 'low'
ELSE 'very_low'
END AS engagement_band
FROM scored;# Assign named score ranges using a window bucket.
More in SQL Window Functions
SQL Window Functions: Performance, EXPLAIN, and Dialect Notes
How to tune window queries, reduce sorts, structure indexes, and account for cross-dialect differences.
SQL Window Functions: Deduplication, Gaps and Islands, and Sessionization
Use ROW_NUMBER, LAG, and running groups to deduplicate rows, detect gaps, and form islands or sessions.
SQL Window Functions: FIRST_VALUE, LAST_VALUE, NTH_VALUE, and Positional Analytics
Positional window functions for first, last, and nth values inside ordered partitions.
SQL Window Functions: LAG, LEAD, Deltas, and Time-Series Comparisons
Compare rows to prior or next rows with LAG and LEAD for change detection, retention, and trend analysis.
SQL Window Functions: Running Totals, Moving Averages, and Cumulative Metrics
Rolling metrics, cumulative sums, moving averages, and period-over-period analytics with frame clauses.
SQL Window Functions: Ranking, Top N per Group, and Percent Rank
Ranking functions such as ROW_NUMBER, RANK, DENSE_RANK, NTILE, PERCENT_RANK, and CUME_DIST.