一尘不染

如何提取中位数?

sql

我需要在“中位数”列中获取中位数。有什么想法吗?

SELECT
MIN(score) min, CAST(AVG(score) AS float) median, MAX(score) max
FROM result JOIN student ON student.id = result.student_id

阅读 241

收藏
2021-05-16

共1个答案

一尘不染

我认为最简单的方法是PERCENTILE_CONT()PERCENTILE_DISC()

SELECT MIN(score) as min_score,
       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY score) as median_score,
       MAX(score) max_score
FROM result r JOIN
     student s
     ON s.id = r.student_id;

假设(合理地)score是数字。

PERCENTILE_CONT()和之间的区别PERCENTILE_DISC()是,当有偶数个值时会发生什么。除非您有少量数据,否则这通常是不重要的考虑因素。

2021-05-16