我想使用
SQLite
计算中位数。我感兴趣的变量是将多个表组合在一起的结果。我尝试遵循此解决方案,但输出显示空值。
我的查询如下:
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
我做错了什么?
似乎您的“CASE”和“AVG”功能不正确。像这样的事情就可以了。
WITH ordered_cte AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY round ORDER BY r) AS rn,
COUNT(*) OVER (PARTITION BY round) AS counter
FROM cte
),
median_cte AS (
SELECT round,
CASE
WHEN counter % 2 = 1 THEN MAX(r) OVER (PARTITION BY round ORDER BY rn ROWS BETWEEN (counter - 1) / 2 AND (counter - 1) / 2)
ELSE AVG(r) OVER (PARTITION BY round ORDER BY rn ROWS BETWEEN counter / 2 - 1 AND counter / 2)
END AS median_r
FROM ordered_cte
)
SELECT round,
COUNT(*) AS n,
ROUND(AVG(r), 3) AS avg_r,
ROUND(MIN(r), 3) AS min_r,
ROUND(MAX(r), 3) AS max_r,
ROUND(MAX(median_r), 3) AS median_r
FROM ordered_cte
GROUP BY round;