0

So i'm having trouble with calculating medians in T-SQL properly.

I've got a CTE that looks like this:

Medians AS (
 SELECT
 ParishCode AS PAR21CD,
 ChangeDate AS 'Month Start',
 PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY Listing_Price) OVER (PARTITION BY ParishCode, ChangeDate) AS Median_Rent
 FROM
 Joined
 GROUP BY
 ParishCode, ChangeDate, Listing_Price
)

This pulls from property level data, so i've got a table with lots of properties and their rental prices, and i want the median rent at Parish level.

However it looks like if one value in Listing_Price repeats (say there are two properties with the same price in the same parish and date) it only uses that value once. If there are many of the same value then that would skew the results.

Am i missing something? I know there is a MEDIAN function but i don't think we have access to it. Is there any way of including all values in the calculation?

asked Mar 7, 2024 at 10:13
3
  • A minimal reproducible example is a great start when asking for SQL assistance. And also add a tag for the dbms used. Commented Mar 7, 2024 at 10:14
  • 2
    What's the purpose of the GROUP BY? Commented Mar 7, 2024 at 10:17
  • 1
    The GROUP BY is messing up your data: PERCENTILE_CONT is calculated after grouping because it's an analytical function not an aggregate. So just remove it. Commented Mar 7, 2024 at 10:30

1 Answer 1

1

As charlieface suggested, the problem was GROUP BY - PERCENTILE_CONT is calculated after grouping because it's an analytical function not an aggregate.

Removing the group by and adding distinct worked in my case.

Medians AS (
 SELECT DISTINCT
 ParishCode AS PAR21CD,
 ChangeDate AS 'Month Start',
 PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY Listing_Price) OVER (PARTITION BY ParishCode, ChangeDate) AS Median_Rent
 FROM
 Joined
)
answered Mar 7, 2024 at 10:43
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.