571 Find Median Given Frequency of Numbers SQL Server with CTE

drop table numbers

create Table numbers (number int,frequency int)

insert into numbers values (0,7)
insert into numbers values (1,1)
insert into numbers values (2,3)
insert into numbers values (3,1)

-- The Numbers table keeps the value of number and its frequency.
--
--+----------+-------------+
--|  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.
--
--+--------+
--| median |
--+--------|
--| 0.0000 |
--+--------+
--
--Write a query to find the median of all numbers and name the result as median.

Solution:

with cte as(
select n.*,sum(frequency) over (order by number) as acc_sum
from numbers n
),cte2 as(
select n.*,c.acc_sum,sum(n.frequency) over() as sum_freq from numbers n
join cte c on n.number=c.number
)
select c2.number as median from cte2 c2
where c2.acc_sum between sum_freq/2 and sum_freq/2+c2.frequency

 

你可能感兴趣的:(571 Find Median Given Frequency of Numbers SQL Server with CTE)