How to use SQL to Calculate the Median | Essential SQL

Опубликовано: 11 Октябрь 2024
на канале: Essential SQL (EssentialSQL)
5,536
122

Joins have got you confused. Then let’s get that fixed! Check out Join Together Now!
https://www.udemy.com/course/join-tog...


You need to calculate the Median using SQL, but one problem! There isn't a MEDIAN() function like there is AVERAGE(). So what do you do? Don't worry! In this video I'll show you how you can use a little used window function PERCENTILE_CONT() to calculate the median.


One Last Thing...
This video is part of my Intermediate Learning series. If you're interested in learning SQL subscribe to @Essential SQL and then check out our Intermediate Learner Playlist. Of course, I also encourage you to visit https://www.essentialsql.com to learn even more!

Most Business Analysts don’t know where to start learning SQL. At Essential SQL we have an easy-to-understand plan. You learn SQL frustration free, at the right time in the right order. Enroll today: https://www.essentialsql.com/landing/...


Important links:
Sample PizzaDB: https://github.com/kwenzel1/Essential...

Corresponding Article:
https://www.essentialsql.com/sql-median/
https://www.essentialsql.com/calculat...


Source Code:
-- Sample Query we'll use
select OrderDate, sum(FinalOrderPrice) TotalSales
from CustomerOrderSummary
group by OrderDate



-- Calculate the Median
select OrderDate, TotalSales,
percentile_cont(.5) within group (order by TotalSales) over() MedianSales
from (
select OrderDate, sum(FinalOrderPrice) TotalSales
from CustomerOrderSummary
group by OrderDate
) d




Course:
https://www.essentialsql.com/landing/...