http://bookshadow.com/weblog/2017/05/01/leetcode-find-median-given-frequency-of-numbers/
The
Numbers
table keeps the value of number and its frequency.
In this table, the numbers are
0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3
, so the median is (0 + 0) / 2 = 0
.
Write a query to find the median of all numbers and name the result as
median
.题目大意:
给定数据表Numbers,包含两列(数字Number及其频率Frequency)
编写查询计算Number的中位数median。
解题思路:
使用MySQL的User-Defined Variables(用户定义变量)。
构造中间表t,包含列Number, Frequency, AccFreq(累积频率), SumFreq(频率求和)
例如样例数据得到的中间表结果为
AccFreq范围在[SumFreq / 2, SumFreq / 2 + Frequency]的Number均值即为答案。
AccFreq范围的推导过程如下:
上式含义为:
两种情况合并即可得到AccFreq的范围: