Leetcode数据库题目-571.给定数字的频率查询中位数

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
    sum(number)/count(distinct number) as median
from(
select
    IF(sum_number%2=0,
       case when (sum_number/2>=@lastcount and sum_number/2<=countn) or (sum_number/2+1>=@lastcount and sum_number/2+1<=countn) then number else null end,
       case when ceil(sum_number/2)>=@lastcount and ceil(sum_number/2)<=countn then number else null end) as number, 
--分奇偶,奇数返回一个就好,偶数考虑散步到两个数字的情况,关键是sum_number/2在该数累计频数和上个数累计频数的区间里
    @lastcount:=countn+1 as lastcount --算上个累计频数结束后,从哪里开始
from(
select
    number,
    frequency,
    @countn:= case when @countn=0 then frequency else @countn+frequency end as countn, --记录累计频数
    sum_number --总共多少数
from
    numbers,(select @countn:=0) b,(select sum(frequency) as sum_number from numbers) s
order by
    number) t, (select @lastcount:=0) t1) t2

你可能感兴趣的:(Leetcode数据库题目-571.给定数字的频率查询中位数)