Simple way to calculate median with MySQL

后端 未结 30 1120
北荒
北荒 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

    Optionally, you could also do this in a stored procedure:

    DROP PROCEDURE IF EXISTS median;
    DELIMITER //
    CREATE PROCEDURE median (table_name VARCHAR(255), column_name VARCHAR(255), where_clause VARCHAR(255))
    BEGIN
      -- Set default parameters
      IF where_clause IS NULL OR where_clause = '' THEN
        SET where_clause = 1;
      END IF;
    
      -- Prepare statement
      SET @sql = CONCAT(
        "SELECT AVG(middle_values) AS 'median' FROM (
          SELECT t1.", column_name, " AS 'middle_values' FROM
            (
              SELECT @row:=@row+1 as `row`, x.", column_name, "
              FROM ", table_name," AS x, (SELECT @row:=0) AS r
              WHERE ", where_clause, " ORDER BY x.", column_name, "
            ) AS t1,
            (
              SELECT COUNT(*) as 'count'
              FROM ", table_name, " x
              WHERE ", where_clause, "
            ) AS t2
            -- the following condition will return 1 record for odd number sets, or 2 records for even number sets.
            WHERE t1.row >= t2.count/2
              AND t1.row <= ((t2.count/2)+1)) AS t3
        ");
    
      -- Execute statement
      PREPARE stmt FROM @sql;
      EXECUTE stmt;
    END//
    DELIMITER ;
    
    
    -- Sample usage:
    -- median(table_name, column_name, where_condition);
    CALL median('products', 'price', NULL);
    

提交回复
热议问题