Lessons › SQL › Deep Dive: Advanced Window Functions
SQL lesson
PERCENTILE_CONT() and PERCENTILE_DISC()
Percentile functions find the value at a specific ranked position in your data.
Try this lesson free →Example
Finding Typical Retail Order Value with Percentiles
SELECT category, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY revenue) AS median_revenue_cont, PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY revenue) AS median_revenue_disc FROM orders GROUP BY category ORDER BY category| category | median_revenue_cont | median_revenue_disc |
|---|---|---|
| Clothing | 61.25 | 55.0 |
| Electronics | 165.0 | 120.0 |
Step by step
- AS gives a column a friendlier name in the result.
SELECT category, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY revenue) AS median_revenue_cont, PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY revenue) AS median_revenue_disc - FROM tells SQL which table to pull the data from.
SELECT category, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY revenue) AS median_revenue_cont, PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY revenue) AS median_revenue_disc FROM orders - GROUP BY collapses rows that share the same value into one row per group.
SELECT category, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY revenue) AS median_revenue_cont, PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY revenue) AS median_revenue_disc FROM orders GROUP BY category
Practice
1. Using orders, write a query to calculate the 50th percentile of revenue.
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY revenue) FROM orders2. Using store_sales, write a query to calculate the 50th percentile of revenue.
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY revenue) FROM store_sales3. Using products, write a query to calculate the 75th percentile of price.
SELECT PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY price) FROM products4. Using employees, write a query to calculate the 75th percentile of salary.
SELECT PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY salary) FROM employees5. Using reviews, write a query to calculate the 50th percentile of rating.
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY rating) FROM reviewsLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →