我想计算一个数字行中的中值.我如何在sqlite 4中这样做?
假设中位数是有序列表中间的元素.
SELECT x FROM MyTable ORDER BY x LIMIT 1 OFFSET (SELECT COUNT(*) FROM MyTable) / 2
当有数量的记录时,通常将中位数定义为两个中间记录的平均值.
在这种情况下,平均值可以这样计算:
SELECT AVG(x) FROM (SELECT x FROM MyTable ORDER BY x LIMIT 2 OFFSET (SELECT (COUNT(*) - 1) / 2 FROM MyTable))
结合奇数和偶数情况,结果如下:
SELECT AVG(x) FROM (SELECT x FROM MyTable ORDER BY x LIMIT 2 - (SELECT COUNT(*) FROM MyTable) % 2 -- odd 1,even 2 OFFSET (SELECT (COUNT(*) - 1) / 2 FROM MyTable))