Simple way to calculate median with MySQL

后端 未结 30 1143
北荒
北荒 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:52

    Another riff on Velcrow's answer, but uses a single intermediate table and takes advantage of the variable used for row numbering to get the count, rather than performing an extra query to calculate it. Also starts the count so that the first row is row 0 to allow simply using Floor and Ceil to select the median row(s).

    SELECT Avg(tmp.val) as median_val
        FROM (SELECT inTab.val, @rows := @rows + 1 as rowNum
                  FROM data as inTab,  (SELECT @rows := -1) as init
                  -- Replace with better where clause or delete
                  WHERE 2 > 1
                  ORDER BY inTab.val) as tmp
        WHERE tmp.rowNum in (Floor(@rows / 2), Ceil(@rows / 2));
    

提交回复
热议问题