当前位置:网站首页>选出表中的中位数记录[构造左右边界 || 问题转换]
选出表中的中位数记录[构造左右边界 || 问题转换]
2022-08-03 18:28:00 【REN_林森】
中位数问题
前言
对于选表中的中位数记录,或者说中位数落在了那一块记录,该如何解?可构造左右边界 || 问题转换(正序累计&反序累计都大于中值时该记录为中位数记录)。
一、中位数问题
二、构造边界 & 问题转换
分两类思想,一类构造左右边界 & 中值;一类问题转化,反向思考,当正序累计 & 逆序累计都大于中值时,则为中位数。
解1:两层view + lead()构造左右边界
with view4base as(
select
grade,
sum(number) over(order by grade) `right`,
sum(number) over() total
from class_grade
),view4lead as(
select
grade,total,
lead(`right` + 1,1) over(order by `right` desc) `left`,`right`
from view4base
)
select grade
from view4lead
where (total >> 1) + 1 >= `left` and (total >> 1) + 1 <= `right`
or total & 1 = 0 and (total >> 1) >= `left` and (total>>1) <= `right`
order by grade
解2:直接做运算得到想要的值–左边界。
with view4base as(
select
grade,
sum(number) over(order by grade) - number `left`,
sum(number) over(order by grade) + 1 `right`,
sum(number) over() total
from class_grade
)
select grade
from view4base
where (total >> 1) + 1 > `left` and (total >> 1) + 1 < `right`
or total & 1 = 0 and (total >> 1) > `left` and (total >> 1) < `right`
order by grade
解3:中位数:n + 1 / 2 和 n / 2 + 1
with view4base as(
select
grade,
sum(number) over(order by grade) - number `left`,
sum(number) over(order by grade) + 1 `right`,
# 中位数:n + 1 / 2 和 n / 2 + 1
sum(number) over() + 1 >> 1 mid1,
(sum(number) over() >> 1) + 1 mid2
from class_grade
)
select grade
from view4base
where mid1 > `left` and mid1 < `right` or mid2 > `left` and mid2 < `right`
order by grade
解4:当一个数正序 & 逆序累计都大于等于中值时(非取整,保留0.5),这个数为中位数。
with view4base as(
select
grade,
sum(number) over(order by grade) m,
sum(number) over(order by grade desc) n,
sum(number) over() / 2 mid
from class_grade
)
select grade
from view4base
where m >= mid and n >= mid
order by grade
总结
1)中位数问题思路,构造左右边界 & 问题转换。
2)抽象能力很重要,不管是聚集函数/窗口函数/内置函数,入参&结果不过可看成一个值,再上面做四则运算/函数等都是OK的,抽象的看待问题。
参考文献
边栏推荐
猜你喜欢
Weekly recommended short video: In order to fill the gap of learning resources, the author specially wrote a book?
online 方式创建索引触发trigger怎么办?
Execution plan of mysql
Mock模拟数据,并发起get,post请求(保姆级教程,一定能成功)
CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes), problem: (D) Magical Array
2021年数据泄露成本报告解读
【牛客在线OJ】-字符逆序
EasyNTS上云网关断电重启后设备离线是什么原因?
Shell:循环语句
Flask框架——项目可安装化
随机推荐
MD5是对称加密还是非对称加密,有什么优缺点
MySQL——增删改查进阶
sys文件系统
Big guy, who is free to help me to see what the problem is, I just read MySQL source print, and I just came into contact with flink.
fatal error: jni.h: No such file or directory
快手通过国际权威信息安全和隐私保护认证,安全能力达到国际领先水平
货比四家 version tb1.63
有人知道flink sql 使用tableEnv.executeSql执行后,怎么获取到任务运行的
SQL代码需要供其他人复用,为什么传统的复制代码不可靠?
VsCode preview Geojson data
[Azure Event Hub] Create Event Hub Consume Client + Custom Event Position with Azure AD Authentication
87.(cesium之家)cesium热力图(贴地形)
调用EasyCVR云台控制接口时,因网络延迟导致云台操作异常该如何解决?
【白话模电2】二极管特性和分类
flink-sql 客户端,咋回事 我show tables 报错
基于ck+redash构建MySQL慢日志+审计日志展示平台
云图说丨初识华为云微服务引擎CSE
首届MogDB征文活动开启啦!
广告电商、泰山众筹、链动2+1,这3个模式到底怎么样?
二叉树求和路径问题解答与注记