Simple way to calculate median with MySQL

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

    Based on @bob's answer, this generalizes the query to have the ability to return multiple medians, grouped by some criteria.

    Think, e.g., median sale price for used cars in a car lot, grouped by year-month.

    SELECT 
        period, 
        AVG(middle_values) AS 'median' 
    FROM (
        SELECT t1.sale_price AS 'middle_values', t1.row_num, t1.period, t2.count
        FROM (
            SELECT 
                @last_period:=@period AS 'last_period',
                @period:=DATE_FORMAT(sale_date, '%Y-%m') AS 'period',
                IF (@period<>@last_period, @row:=1, @row:=@row+1) as `row_num`, 
                x.sale_price
              FROM listings AS x, (SELECT @row:=0) AS r
              WHERE 1
                -- where criteria goes here
              ORDER BY DATE_FORMAT(sale_date, '%Y%m'), x.sale_price
            ) AS t1
        LEFT JOIN (  
              SELECT COUNT(*) as 'count', DATE_FORMAT(sale_date, '%Y-%m') AS 'period'
              FROM listings x
              WHERE 1
                -- same where criteria goes here
              GROUP BY DATE_FORMAT(sale_date, '%Y%m')
            ) AS t2
            ON t1.period = t2.period
        ) AS t3
    WHERE 
        row_num >= (count/2) 
        AND row_num <= ((count/2) + 1)
    GROUP BY t3.period
    ORDER BY t3.period;
    

提交回复
热议问题