MySQL:求众数、平均数、中位数

目录

  • 1.样例表
  • 2.众数
    • 2.1使用having
    • 2.2使用视图+max
  • 3.平均数
    • 3.1直接sum/count
    • 3.2使用avg
  • 4.中位数

1.样例表

ceshi_salaries表中字段如下所示
MySQL:求众数、平均数、中位数_第1张图片

2.众数

以求员工工资的众数为例

2.1使用having

首先用COUNT()对工资计数,找到出现最多的次数

SELECT COUNT(*) 
FROM ceshi_salaries 
GROUP BY salary

再用嵌套即可

SELECT salary,COUNT(*) AS cnt
FROM ceshi_salaries
GROUP BY salary
HAVING count(*) >= ALL(SELECT COUNT(*) FROM ceshi_salaries GROUP BY salary) 

补充ALL、IN和ANY的用法

  1. IN:在范围内的值,只要有就true;
  2. ALL:与子查询返回的所有值比较为true,则返回true;
  3. ANY:与子查询返回的任何值比较为true,只有有一个成立,则返回true;

2.2使用视图+max

create view max_a as -- 创建视图
SELECT salary,COUNT(*) as nt
FROM ceshi_salaries 
GROUP BY salary;
select salary,nt
from max_a
where nt=(select max(nt) from max_a)

3.平均数

3.1直接sum/count

SELECT SUM(salary)/COUNT(DISTINCT emp_no) AS avg_salary
FROM ceshi_salaries

3.2使用avg

SELECT AVG(a.salary)
FROM
	(SELECT SUM(salary) AS salary
	 FROM ceshi_salaries
	 GROUP BY emp_no) AS a

4.中位数

SELECT AVG(DISTINCT a.salary) AS median_salary
FROM
	(SELECT a.salary
	 FROM ceshi_salaries AS a, ceshi_salaries AS b
	 GROUP BY a.salary
	 HAVING SUM(CASE WHEN b.salary >= a.salary THEN 1 ELSE 0 END) >= COUNT(*) / 2 
	 AND SUM(CASE WHEN b.salary <= a.salary THEN 1 ELSE 0 END) >= COUNT(*) / 2 ) AS a;

你可能感兴趣的:(SQL,数据库,mysql)