Median of multiple columns in MySql

405 views Asked by At

How do you get the median of a row in MySQL?

I have a table which gives monthly stock for a series of categories:

cat_id | mar_stk | feb_stk | jan_stk
1      | 5       | 7       | 9
2      | 2       | 1       | 3
3      | 6       | 8       | 10

I need the median, maximum and minimum stock for each category.

Currently have minimum and maximum using:

SELECT
    cat_id,
    GREATEST(mar_stk, feb_stk, jan_stk) AS max_stk,
    LEAST(mar_stk, feb_stk, jan_stk) AS min_stk

FROM example_table

Which leaves me with:

cat_id | max_stk | min_stk
1      | 9       | 5
2      | 3       | 1
3      | 10      | 6

But I can't find any straightforward way to find the median.

1

There are 1 answers

2
Sectona On

By statistics, Median is the middle number in a given out distribution. For instance if in the column cat_id where you have value 1,2,3 etc. Your median is 2 since its the number or value at the middle. Query the middle value and then hurray. Give me a shout if you still need further guide. ..Sectona