gpt4 book ai didi

mysql - 计算 MySQL 中列的简单中位数

转载 作者:行者123 更新时间:2023-12-05 02:47:52 25 4
gpt4 key购买 nike

我正在努力为一个简单的中位数问题找到解决方案。给定一个只有一列的表 my_table:

my_column | 
----------|
10 |
20 |
30 |
40 |
50 |
60 |

如何调用函数返回 35 的中位数?

当我只想返回中值时,我无法弄清楚如何使此语法起作用:

SELECT
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY my_column) OVER ( PARTITION BY my_column)
FROM
my_table

最佳答案

这是我在 MySQL 8.0 中测试的解决方案:

with ranked as (
select my_column,
row_number() over (order by my_column) as r,
count(my_column) over () as c
from my_table
),
median as (
select my_column
from ranked
where r in (floor((c+1)/2), ceil((c+1)/2))
)
select avg(my_column) from median

输出:

+----------------+
| avg(my_column) |
+----------------+
| 35.0000 |
+----------------+

我借用了https://stackoverflow.com/a/7263925/20860的方法但使其适用于 MySQL 8.0 CTE 和窗口函数。

关于mysql - 计算 MySQL 中列的简单中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64755680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com