My question is quite similar to this, but instead of the mean, I need to find the median value over different columns of a row (in order to identify some outliers).
Suppose I have the following table:
X Y Z
-------------
6 3 3
5 6 NULL
4 5 6
11 7 8
What I need is:
MEDIAN
-------------
3
5 or 5.5
5
8
In case of an even number of non-NULL elements, the median could be just one of the central values or the average. I don’t care so much about that, any version would be fine for me.
Ideally, I would like to define this solution as a PostgreSQL-function, so that I can simply use it like GREATEST/LEAST, but any idea would be appreciated.
2
Answers
Flipping it to
jsonb
and then back so as to use thepercentile_cont()
function is a lazy way to do this:Working fiddle
As a function, using an array and sorting it with the extension intarray, it could be done like this:
Fiddle to test here