Simple way to calculate median with MySQL

后端 未结 30 1121
北荒
北荒 2020-11-22 04:20

What\'s the simplest (and hopefully not too slow) way to calculate the median with MySQL? I\'ve used AVG(x) for finding the mean, but I\'m having a hard time fi

30条回答
  •  醉话见心
    2020-11-22 04:57

    If MySQL has ROW_NUMBER, then the MEDIAN is (be inspired by this SQL Server query):

    WITH Numbered AS 
    (
    SELECT *, COUNT(*) OVER () AS Cnt,
        ROW_NUMBER() OVER (ORDER BY val) AS RowNum
    FROM yourtable
    )
    SELECT id, val
    FROM Numbered
    WHERE RowNum IN ((Cnt+1)/2, (Cnt+2)/2)
    ;
    

    The IN is used in case you have an even number of entries.

    If you want to find the median per group, then just PARTITION BY group in your OVER clauses.

    Rob

提交回复
热议问题