gpt4 book ai didi

MySQL:计算中值

转载 作者:行者123 更新时间:2023-11-29 06:51:10 26 4
gpt4 key购买 nike

我正在尝试计算价格的中位数。我在这里找到了如何做的答案- Simple way to calculate median with MySQL ,但这对我不起作用,我得到的结果是空的。谁能帮忙?

SELECT x.price from mediana as x, mediana y
GROUP BY x.price
HAVING SUM(SIGN(1-SIGN(y.price-x.price))) = (COUNT(*)+1)/2

最佳答案

AFAIU 你的问题。

This answer @velcrow 成功计算中值。不幸的是,当行数为偶数而不是计算中间 2 行的平均值时,查询只返回第二个值。我已对查询进行了一些修改以满足您的需要:

--average value for middle rows
SELECT avg(t1.price) as median_val FROM (
SELECT @rownum:=@rownum+1 as `row_number`, d.price
FROM mediana d, (SELECT @rownum:=0) r
WHERE 1
-- put some where clause here
ORDER BY d.price
) as t1,
(
SELECT count(*) as total_rows
FROM mediana d
WHERE 1
-- put same where clause here
) as t2
WHERE 1
--this condition should return one record for odd number of rows and 2 middle records for even.
AND t1.row_number>=total_rows/2 and t1.row_number<=total_rows/2+1;

Test on sample data on sqlfiddle

关于MySQL:计算中值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15338584/

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