-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode571.sql
More file actions
75 lines (74 loc) · 1.62 KB
/
LeetCode571.sql
File metadata and controls
75 lines (74 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
with
t1 as (
select sum(frequency) sums, (
CASE
when sum(frequency) % 2 = 0 then "even"
else "odd"
end
) odd_even
from Numbers
),
t2 as (
select num, frequency, sum(frequency) over (
order by num
) after_cum
from Numbers
),
t3 as (
select num, after_cum, (
LAG(after_cum, 1, 0) over (
order by num
)
) before_cum
from t2
)
select avg(num) median
from t3
where (
(
select odd_even
from t1
) = "odd"
and (
before_cum < (
(
select sums
from t1
) + 1
) / 2
and after_cum >= (
(
select sums
from t1
) + 1
) / 2
)
)
or (
(
select odd_even
from t1
) = "even"
and (
(
before_cum < (
select sums
from t1
) / 2
and after_cum >= (
select sums
from t1
) / 2
)
or (
before_cum < (
select sums
from t1
) / 2 + 1
and after_cum >= (
select sums
from t1
) / 2 + 1
)
)
);