欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode-SQL-571. 给定数字的频率查询中位数

程序员文章站 2022-06-11 14:28:58
...

LeetCode-SQL-571. 给定数字的频率查询中位数

LeetCode-SQL-571. 给定数字的频率查询中位数

Create table If Not Exists Numbers (Number int, Frequency int)
Truncate table Numbers
insert into Numbers (Number, Frequency) values ('0', '7')
insert into Numbers (Number, Frequency) values ('1', '1')
insert into Numbers (Number, Frequency) values ('2', '3')
insert into Numbers (Number, Frequency) values ('3', '1')
SELECT avg(Number) as median
FROM
(
SELECT Number,Frequency,
@pre_num:=Number,
@rank_down:aaa@qq.com_up as rank_down,
@rank_up:aaa@qq.com_down+Frequency as rank_up
FROM
Numbers n, (SELECT @pre_num:=0,@rank_down:=0,@rank_up:=0) t
ORDER BY Number
) A
,
(

SELECT CEIL(SUM(Frequency)/2) as beg, IF(SUM(Frequency) mod 2=0,1,0) as cnt
FROM Numbers

) B
WHERE A.rank_up >=B.beg and A.rank_down <B.beg+B.cnt

 

相关标签: LeetCode 数据库