Skip to content

Latest commit

 

History

History
92 lines (71 loc) · 2.09 KB

File metadata and controls

92 lines (71 loc) · 2.09 KB

English Version

题目描述

Numbers 表:

+-------------+------+
| Column Name | Type |
+-------------+------+
| num         | int  |
| frequency   | int  |
+-------------+------+
num 是这张表的主键(具有唯一值的列)。
这张表的每一行表示某个数字在该数据库中的出现频率。

 

中位数 是将数据样本中半数较高值和半数较低值分隔开的值。

编写解决方案,解压 Numbers 表,报告数据库中所有数字的 中位数 。结果四舍五入至 一位小数

返回结果如下例所示。

 

示例 1:

输入: 
Numbers 表:
+-----+-----------+
| num | frequency |
+-----+-----------+
| 0   | 7         |
| 1   | 1         |
| 2   | 3         |
| 3   | 1         |
+-----+-----------+
输出:
+--------+
| median |
+--------+
| 0.0    |
+--------+
解释:
如果解压这个 Numbers 表,可以得到 [0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3] ,所以中位数是 (0 + 0) / 2 = 0 。

解法

方法一:开窗函数

SQL

# Write your MySQL query statement below
WITH
    t AS (
        SELECT
            *,
            SUM(frequency) OVER (ORDER BY num ASC) AS rk1,
            SUM(frequency) OVER (ORDER BY num DESC) AS rk2,
            SUM(frequency) OVER () AS s
        FROM Numbers
    )
SELECT
    ROUND(AVG(num), 1) AS median
FROM t
WHERE rk1 >= s / 2 AND rk2 >= s / 2;

...