I want to calculate the median using SQLite
. My variable of interest is the result of combining multiple tables together. I tried to follow this solution, but the output shows null-values.
My query looks as follows:
WITH cte AS (
SELECT m.round,
f.f * (m.won * o.odds - 1) AS r
FROM matches m
INNER JOIN f
ON f.match_id = m.match_id
AND f.player_id = m.player_id
INNER JOIN odds o
ON o.match_id = m.match_id
AND o.player_id = m.player_id
)
SELECT round,
COUNT(*) AS n,
ROUND(AVG(r), 3) AS avg_r,
ROUND(AVG(
CASE counter % 2
WHEN 0 THEN CASE WHEN rn IN (counter / 2, counter / 2 + 1) THEN r END
WHEN 1 THEN CASE WHEN rn = counter / 2 + 1 THEN r END
END
) OVER (PARTITION BY round), 3) median_r,
ROUND(MIN(r), 3) AS min_r,
ROUND(MAX(r), 3) AS max_r
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY round ORDER BY r) rn,
COUNT(*) OVER (PARTITION BY round) counter
FROM cte)
GROUP BY round
What am I doing wrong?