Simple way to calculate median with MySQL

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

    Often, we may need to calculate Median not just for the whole table, but for aggregates with respect to our ID. In other words, calculate median for each ID in our table, where each ID has many records. (good performance and works in many SQL + fixes problem of even and odds, more about performance of different Median-methods https://sqlperformance.com/2012/08/t-sql-queries/median )

    SELECT our_id, AVG(1.0 * our_val) as Median
    FROM
    ( SELECT our_id, our_val, 
      COUNT(*) OVER (PARTITION BY our_id) AS cnt,
      ROW_NUMBER() OVER (PARTITION BY our_id ORDER BY our_val) AS rn
      FROM our_table
    ) AS x
    WHERE rn IN ((cnt + 1)/2, (cnt + 2)/2) GROUP BY our_id;
    

    Hope it helps

提交回复
热议问题