[SQL]给定数字的频率查询中位数
Posted wyz-2020
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[SQL]给定数字的频率查询中位数相关的知识,希望对你有一定的参考价值。
571. 给定数字的频率查询中位数
思路
数字个数可由n = SUM(frequency)求得,
先创建两列。asc_frequency:记录小于等于当前number的数字个数;desc_frequency:记录大于等于当前number的数字个数
这么创建的原因是,当我们找到asc_frequency中对应>=n/2,且在desc_frequency中>=n/2的对应的number。
如果有两个,则取平均AVG(number)为median
步骤
- 建立临时表t
2.选取asc_frequency中对应>=n/2,且在desc_frequency中>=n/2的对应的number
WHERE t.asc_frequency >= (SELECT SUM(Frequency) FROM Numbers)/2
AND t.desc_frequency >= (SELECT SUM(Frequency) FROM Numbers)/2
- 如果有多个数,返回Number的平均
SELECT AVG(Number) AS median
FROM () t
WHERE ...
代码
SELECT AVG(Number) AS median
FROM (SELECT n1.Number, n1.Frequency,
(SELECT SUM(Frequency) FROM numbers n2 WHERE n2.Number<=n1.Number) AS asc_frequency,
(SELECT SUM(Frequency) FROM numbers n3 WHERE n3.Number>=n1.Number) AS desc_frequency
FROM numbers n1) t
WHERE t.asc_frequency >= (SELECT SUM(Frequency) FROM Numbers)/2
AND t.desc_frequency >= (SELECT SUM(Frequency) FROM Numbers)/2 ;
以上是关于[SQL]给定数字的频率查询中位数的主要内容,如果未能解决你的问题,请参考以下文章