sql求中位数


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

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

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. 窗口函数:根据中位数的位置信息进行求解

  • 分奇偶条件判断
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

  • 中位数条件由排序和总和计算
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. 中位数,正排倒排都是中位数

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’

或者修改代码

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 求中位数

相关推荐

  1. sql位数

    2024-02-04 16:04:02       57 阅读
  2. hive如何位数

    2024-02-04 16:04:02       65 阅读
  3. 两个等长数组的位数

    2024-02-04 16:04:02       42 阅读
  4. N个整数的平均数、众数和位数

    2024-02-04 16:04:02       31 阅读
  5. SQL:同时在线人数问题

    2024-02-04 16:04:02       41 阅读
  6. openJudge | 位数 C语言

    2024-02-04 16:04:02       58 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-04 16:04:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-04 16:04:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-04 16:04:02       87 阅读
  4. Python语言-面向对象

    2024-02-04 16:04:02       96 阅读

热门阅读

  1. LeetCode803. Bricks Falling When Hit——洪水填充

    2024-02-04 16:04:02       47 阅读
  2. vue中$refs的用法及作用详解

    2024-02-04 16:04:02       45 阅读
  3. C# 从“byte[]”转换为“BitmapImage”

    2024-02-04 16:04:02       58 阅读
  4. openEuler 22.03 docker安装elasticsearch 7.17.17

    2024-02-04 16:04:02       41 阅读
  5. 美敦力呼吸机PB560硬件分析

    2024-02-04 16:04:02       56 阅读
  6. [C语言]结构体初识

    2024-02-04 16:04:02       56 阅读
  7. Large Language Models on Graphs: A Comprehensive Survey

    2024-02-04 16:04:02       60 阅读
  8. 在 Qt 中如何将数字转换为QString

    2024-02-04 16:04:02       52 阅读
  9. 栈和队列-删除字符串中的所有相邻重复项

    2024-02-04 16:04:02       55 阅读
  10. 蓝桥杯题目-四个瓷瓶的神秘游戏

    2024-02-04 16:04:02       58 阅读