0

I have a table with a list of 499 positive non-integer numbers N, I want to find the median of these numbers and I have below:

SELECT (ROUND(N,4)) FROM TABLE ORDER BY N LIMIT 1 OFFSET ((COUNT(N)-1)/2);

I get the following error:

"ERROR 1064 (42000) at line 15: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '((COUNT(N)-1)/2)' at line 4"

This works if I replace ((COUNT(N)-1)/2) by 249 (where the median would be after table is ordered), so I can't use ((COUNT(N)-1)/2). Why is this? What should I put instead to find the median?

Thanks

1

2 Answers 2

1

Alas, you cannot include expressions in the limit. You could count the number of rows in the table and then pass that in as the limit.

I would normally use:

select avg(n)
from (select t.*, (@rn := @rn + 1) as rn
      from (select t.*
            from t
            order by n
           ) t cross join
           (select @rn := 0) params
     ) t
where 2 * rn in (@rn - 1, @rn, @rn + 1);

Notes:

  • The additional level of subqueries is needed in the most recent versions of MySQL -- parameters do not always mix with order by.
  • The where works for both even and odd numbers of rows.
  • The avg() takes the middle point when the number of rows is even.
0

It's a bit complex, you need to creta a index aligned with your data and after catch it

SELECT 
*
FROM
(SELECT 
    t.*, @rownum:=@rownum + 1 AS rank
FROM
    myTabel t, (SELECT @rownum:=0) r
ORDER BY ColumnToSort) AS B
WHERE
     B.rank = (SELECT 
             ROUND(COUNT(*) / 2, 0)
        FROM
             myTable)

Basically, you want get the row with row number equal of half of selection. MySql doesn't supports any function that return this value so you need to make yourself. A very good reference can found here (MySQL - Get row number on select)

The main code is behind this few code line:

SELECT 
    t.*, @rownum:=@rownum + 1 AS rank
FROM
    myTabel t, (SELECT @rownum:=0) r
ORDER BY ColumnToSort

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.