sql求中位数

sql求解中位数

  • [1. 窗口函数:根据中位数的位置信息进行求解](#1. 窗口函数:根据中位数的位置信息进行求解)
  • [2. 中位数,正排倒排都是中位数](#2. 中位数,正排倒排都是中位数)

中位数是指有序数列中,位于 中间位置 的数的值
若为奇数,则中间数开始位置=结束位置
若为偶数,则中位数结束位置-开始位置=1

求解公司员工薪水的中位数

sql 复制代码
select  com_id, floor((count(salary)+1)/2) as start,
floor((count(salary)+2)/2) as end
from employee group by com_id order by com_id

1. 窗口函数:根据中位数的位置信息进行求解

  • 分奇偶条件判断
sql 复制代码
select com_id,salary
from
	(
	select com_id,
	salary,
	row_number() over(partition by com_id order by salary desc) as rnk,
	count(salary) over(partition by com_id) as num
	from employee 
	) t1
where t1.rnk in (floor(num/2)+1, if(mod(num,2)=0,floor(num/2),floor(num/2)+1)
order by com_id
  • 中位数条件由排序和总和计算
sql 复制代码
select com_id, salary
from
(
	select com_id,salary,
	row_number() over(partition by com_id order by salary Desc) rnk,
	count(salary) over(partition by com_id) as num
	from employee
) t1
where abs(t1.rnk - (t1.num+1)/2) < 1
order by com_id

注意:不可在一次查询中对窗口函数的结果进行操作

因为查询的顺序为:from->where->group by->having->select->order by

2. 中位数,正排倒排都是中位数

sql 复制代码
select com_id,salary
from
(
	select *,
	row_number() over(partition by com_id order by salary) as rnk1,
	row_number() over(partition by com_id order by salary desc) as rnk2
	from employee
) t1
where rnk1=rnk2 or abs(rnk1-rnk2)=1
order by com_id

报错:BIGINT UNSIGNED value is out of range

两种方式修改:

直接修改设置SET sql_mode='NO_UNSIGNED_SUBTRACTION'

或者修改代码

sql 复制代码
select com_id,salary
from
(
	select *,
	row_number() over(partition by com_id order by salary) as rnk1,
	row_number() over(partition by com_id order by salary desc) as rnk2
	from employee
) t1
where t1.rnk1 = t1.rnk2 or abs(cast(t1.rnk1 as signed)-cast(t1.rnk2 as signed)) = 1

ref:SQL 求中位数

相关推荐
云飞云共享云桌面28 分钟前
医疗器械设备研发:多人同时操作 SolidWorks,怎样依靠单台服务器替代多工作站
运维·服务器·网络·数据库·制造
知行合一。。。6 小时前
RAG--03--Milvus基本用法
数据库·oracle·milvus
TDengine (老段)6 小时前
TDengine 线程模型 — 网络、调度、执行
大数据·数据库·物联网·制造·时序数据库·tdengine·涛思数据
上学的小垃圾7 小时前
01-数据库系统概述
数据库
二进制漫游记8 小时前
FastAPI项目集成 Qdrant向量数据库+阿里云Embedding完整实战(工具封装+业务调用)
数据库·python·阿里云·embedding
2501_928996228 小时前
GPT-4o换DeepSeek迁移成本多少?中科热备解析API聚合平台技术账本
前端·数据库·人工智能
泡干脆面就番茄10 小时前
MySQL_子查询_分页查询与联合查询详解
数据库·mysql
devpotato11 小时前
缓存与数据库更新顺序不一致问题
java·数据库·redis
天若有情67311 小时前
Node+MySQL小型全栈笔记项目实战课程分享
数据库·笔记·mysql
wxwx_bscxy32212 小时前
基于springboot宠物领养系统的设计与实现
数据库·spring boot·后端·spring·宠物