1
2WITH combined_prices AS (
3 SELECT variety, price FROM winemag_p1
4 UNION ALL
5 SELECT variety, price FROM winemag_p2
6),
7
8
9ranked_prices AS (
10 SELECT
11 variety,
12 price,
13 ROW_NUMBER() OVER (PARTITION BY variety ORDER BY price) AS rn_asc,
14 COUNT(*) OVER (PARTITION BY variety) AS total_count
15 FROM
16 combined_prices
17),
18
19
20odd_rows AS (
21 SELECT
22 variety,
23 price
24 FROM
25 ranked_prices
26 WHERE
27 rn_asc = (total_count / 2) + 1
28 AND total_count % 2 <> 0
29),
30
31
32even_rows AS (
33 SELECT
34 variety,
35 AVG(price) AS price
36 FROM
37 ranked_prices
38 WHERE
39 rn_asc IN (total_count / 2, (total_count / 2) + 1)
40 AND total_count % 2 = 0
41 GROUP BY
42 variety
43),
44
45
46median_prices AS (
47 SELECT * FROM odd_rows
48 UNION ALL
49 SELECT * FROM even_rows
50)
51
52
53SELECT
54 variety,
55 price AS median_price
56FROM
57 median_prices
58ORDER BY
59 variety;
60