Find Median Given Frequency Of Numbers Problem
Description
LeetCode Problem 571.
The Numbers table keeps the value of number and its frequency.
1
2
3
4
5
6
7
8
+----------+-------------+
| Number | Frequency |
+----------+-------------|
| 0 | 7 |
| 1 | 1 |
| 2 | 3 |
| 3 | 1 |
+----------+-------------+
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.
1
2
3
4
5
+--------+
| median |
+--------|
| 0.0000 |
+--------+
Write a query to find the median of all numbers and name the result as median.
MySQL Solution
1
2
3
4
5
6
select round(sum(Number) / count(Number), 2) as median
from (select Number, Frequency,
sum(Frequency) over (order by Number) as cumulative_num,
sum(Frequency) over () as total_num
from Numbers) sub
where total_num / 2.0 between cumulative_num - Frequency and cumulative_num
LeetCode Database - Hard
LeetCode 185
LeetCode 262
LeetCode 569
LeetCode 571
LeetCode 579
LeetCode 601
LeetCode 615
LeetCode 618
LeetCode 1097
LeetCode 1127
LeetCode 1159
LeetCode 1194
LeetCode 1225
LeetCode 1336
LeetCode 1369
LeetCode 1384
LeetCode 1412
LeetCode 1479
LeetCode 1635
LeetCode 1645
LeetCode 1651
LeetCode 1767
LeetCode 1892
LeetCode 1917
LeetCode 1919
LeetCode 1972
More LeetCode Database
MySQL Tutorials