mysql 求中位数、四分位数

CREATE TABLE `student_t` (
  `id` varchar(32) NOT NULL,
  `value` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 
insert into student_t (id,`value`) 
values ('A',40),
('B',50),
('C',60),
('D',70),
('E',80),
('F',90);
  • 第一步先给表加一个列,列里面是对分数的排序(即标明了位置)
SELECT
		id,
		@INDEX := @INDEX + 1 AS myindex,
		`VALUE` -- myindex代表的是这一列数,@index是位置
		
	FROM
		student_t
		INNER JOIN ( SELECT @INDEX := 0 ) AS initvar ON 1 = 1 
	ORDER BY
		`VALUE` #最内层

mysql 求中位数、四分位数_第1张图片

  • 当记录是奇数时,中位数中间位置的数;当记录是偶数时,中位数是中间两个数的平均
	SELECT
	GROUP_CONCAT( id ),
	avg( `VALUE` ) 
FROM
	(#第二层开始
	SELECT
		id,
		@INDEX := @INDEX + 1 AS myindex,
		`VALUE` -- myindex代表的是这一列数,@index是位置	
	FROM
		student_t
		INNER JOIN ( SELECT @INDEX := 0 ) AS initvar ON 1 = 1 
	ORDER BY
		`VALUE` #最内层	
	) AS t 
WHERE
	myindex = floor( @INDEX / 2+1 )  OR myindex = ceil( @INDEX / 2 )
  • 四分位数
	SELECT
	GROUP_CONCAT( id ),
	avg( `VALUE` ) 
FROM
	(#第二层开始
	SELECT
		id,
		@INDEX := @INDEX + 1 AS myindex,
		`VALUE` -- myindex代表的是这一列数,@index是位置	
	FROM
		student_t
		INNER JOIN ( SELECT @INDEX := 0 ) AS initvar ON 1 = 1 
	ORDER BY
		`VALUE` #最内层	
	) AS t 
WHERE
	myindex = floor(( @INDEX+1) /4 ) 
	SELECT
	GROUP_CONCAT( id ),
	avg( `VALUE` ) 
FROM
	(#第二层开始
	SELECT
		id,
		@INDEX := @INDEX + 1 AS myindex,
		`VALUE` -- myindex代表的是这一列数,@index是位置	
	FROM
		student_t
		INNER JOIN ( SELECT @INDEX := 0 ) AS initvar ON 1 = 1 
	ORDER BY
		`VALUE` #最内层	
	) AS t 
WHERE
	myindex = floor(3*( @INDEX+1) /4 ) 

扫码关注更多的分享内容,祝好呀~~

你可能感兴趣的:(Mysql)