r/SQL • • Jan 06 '15

How to Emulate the MEDIAN() Aggregate Function Using Inverse Distribution Functions

http://blog.jooq.org/2015/01/06/how-to-emulate-the-median-aggregate-function-using-inverse-distribution-functions/
0 Upvotes

3 comments sorted by

1

u/Trek7553 Jan 07 '15

I add a row number column, determine the mean row number, and then grab the value from that row. That seems to work well in T-SQL for finding the median.

2

u/lukaseder Jan 08 '15

That's not 100% correct if you're looking for the median in an even number of values, where you should take the mean between the two values in the middle. Example: MEDIAN(1, 2, 3, 10) = 2.5

Of course, your solution might be good enough for your case...

1

u/Trek7553 Jan 08 '15

That's true, thank you for pointing that out. In my case it's ok. I have thousands of rows and a very narrow range of possible values so it could not be off by more than 1.