[tbl_votes]
- id <!-- unique id of the vote) -->
- item_id <!-- vote belongs to item <id> -->
- vote <!-- number 1-10 -->
当然我们可以通过以下方式解决这个问题:
最小观察值
(so)下四分位数
(lq)中位数
(我)上四分位数
(uq)- 和
最大观察
(lo)
..逐个使用多个查询,但我想知道是否可以通过单个查询完成。
在 Oracle 中,我可以使用 COUNT OVER
和 RATIO_TO_REPORT
,但这在 mySQL 中不受支持。
对于那些不知道箱线图是什么的人:http://en.wikipedia.org/wiki/Box_plot
如有任何帮助,我们将不胜感激。
最佳答案
我在 PostgreSQL 中找到了一个使用 PL/Python 的解决方案。
但是,我将问题悬而未决,以防其他人在 mySQL 中提出解决方案。
CREATE TYPE boxplot_values AS (
min numeric,
q1 numeric,
median numeric,
q3 numeric,
max numeric
);
CREATE OR REPLACE FUNCTION _final_boxplot(strarr numeric[])
RETURNS boxplot_values AS
$$
x = strarr.replace("{","[").replace("}","]")
a = eval(str(x))
a.sort()
i = len(a)
return ( a[0], a[i/4], a[i/2], a[i*3/4], a[-1] )
$$
LANGUAGE 'plpythonu' IMMUTABLE;
CREATE AGGREGATE boxplot(numeric) (
SFUNC=array_append,
STYPE=numeric[],
FINALFUNC=_final_boxplot,
INITCOND='{}'
);
示例:
SELECT customer_id as cid, (boxplot(price)).*
FROM orders
GROUP BY customer_id;
cid | min | q1 | median | q3 | max
-------+---------+---------+---------+---------+---------
1001 | 7.40209 | 7.80031 | 7.9551 | 7.99059 | 7.99903
1002 | 3.44229 | 4.38172 | 4.72498 | 5.25214 | 5.98736
来源:http://www.christian-rossow.de/articles/PostgreSQL_boxplot_median_quartiles_aggregate_function.php
关于mysql - 如何使用 1 个 mySQL 查询返回所有结果的数值箱线图数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8639073/