Skip to content
Advertisement

With MySQL, how to calculate a MEDIAN with Left Join records?

Given the following two tables, I’d like to know how to calculate the MEDIAN rating for reviews on a weekly basis.

reviews

reviews_areas

Example Data:

reviews:

reviews_areas:

Advertisement

Answer

The problem is not clear. I’ll use reviews.completed_at for the date because reviews_areas.created_at contains just a time.

We need to join reviews for the date with reviews_areas for the rating.

To avoid the same week on different years from overlapping, we use yearweek to turn dates into the year + week.

To get the median we need to find the middle row (or rows if there’s an even number) for each week. There’s many ways to do this. I’ll crib from Justin Grant’s clever answer. We count the row_number() ordered ascending and descending. Where they overlap +/- 1 are the median rows. Then we average them.

First, we get the row numbers by week.

The row numbers are ordered by order by rating asc, id asc. The id is a secondary sort to disambiguate rows with the same rating.

Then we use that as a common table expression to average the middle rows of each week. A subquery works just as well.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement