用mysql 写一个存储过程有一个7个数的数组字符串11121914151612找出此符串里的最大值并且从最大值所在位置往前的数值为一级数值计算回归线的斜率
DELIMITER $$ CREATE PROCEDURE calculate_slope(IN array_str VARCHAR(255), OUT slope FLOAT) BEGIN DECLARE max_val INT; DECLARE max_index INT; DECLARE vals INT; DECLARE i INT DEFAULT 1; DECLARE x_sum FLOAT DEFAULT 0; DECLARE y_sum FLOAT DEFAULT 0; DECLARE xy_sum FLOAT DEFAULT 0; DECLARE x_square_sum FLOAT DEFAULT 0; DECLARE y_square_sum FLOAT DEFAULT 0;
-- Convert the array string into a table
CREATE TEMPORARY TABLE IF NOT EXISTS temp_table (val INT);
SET @sql = CONCAT('INSERT INTO temp_table VALUES(', REPLACE(array_str, ',', '),('), ');');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- Find the maximum value and its index in the array
SELECT MAX(val), FIND_IN_SET(MAX(val), GROUP_CONCAT(val)) INTO max_val, max_index FROM temp_table;
-- Calculate the values before the maximum value
SET vals = max_index - 1;
-- Calculate the sums for the regression line
WHILE i <= vals DO
SELECT val INTO @x FROM temp_table WHERE ROWID = i;
SET x_sum = x_sum + @x;
SET x_square_sum = x_square_sum + @x * @x;
SELECT val INTO @y FROM temp_table WHERE ROWID = i + 1;
SET y_sum = y_sum + @y;
SET y_square_sum = y_square_sum + @y * @y;
SET xy_sum = xy_sum + @x * @y;
SET i = i + 1;
END WHILE;
-- Calculate the slope of the regression line
SET slope = (vals * xy_sum - x_sum * y_sum) / (vals * x_square_sum - x_sum * x_sum);
-- Drop the temporary table
DROP TEMPORARY TABLE IF EXISTS temp_table;
END$$ DELIMITER ;
-- Example usage: CALL calculate_slope('11,12,19,14,15,16,12', @slope); SELECT @slope; -- This will return the calculated slope value.
原文地址: http://www.cveoy.top/t/topic/bWe0 著作权归作者所有。请勿转载和采集!