Leetcode_数据库刷题_571. 给定数字的频率查询中位数

571题. 给定数字的频率查询中位数
SQL架构:

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')

Numbers 表保存数字的值及其频率。

Number Frequency
0 7
1 1
2 3
3 1

在此表中,数字为 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3,所以中位数是 (0 + 0) / 2 = 0。

median
0.0000

问题:请编写一个查询来查找所有数字的中位数并将结果命名为 median 。
解答

select avg(Number) as median from
(
    select Number,Frequency, sum(Frequency) over(order by Number ) as s1,
       sum(Frequency) over(order by number desc) as s2,
       sum(Frequency) over() as s3 from Numbers
    order by Number  
) tmp
where s1 >= s3/2 and s2 >= s3/2;

1、中位数可以理解为某一数的正序和逆序累计均大于等于整个序列的数字个数的一半
2、 sum() over()用法见:511.游戏玩法分析III方法二说明

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-median-given-frequency-of-numbers

你可能感兴趣的:(Leetcode_数据库刷题,sql)