PostgreSQL多参数聚合函数

7
我一直在努力理解如何在PostgreSQL(8.4或9.1)中创建接受一个或多个可选参数的聚合函数。
例如,创建一个PL/R扩展程序来计算p分位数,其中0 <= p <= 1。这将类似于quantile(x,p),并且作为查询的一部分:
select category,quantile(x,0.25)
from TABLE
group by category
order by category;

TABLE (category:text, x:float) 中。

有什么建议吗?

2个回答

8
希望这个例子能帮到你。你需要一个函数,它接受(累加器,聚合参数)并返回新的累加器值。尝试运行下面的代码,这样你就可以感受到它们是如何组合在一起的。
BEGIN;

CREATE FUNCTION sum_product_fn(int,int,int) RETURNS int AS $$
    SELECT $1 + ($2 * $3);
$$ LANGUAGE SQL;           

CREATE AGGREGATE sum_product(int, int) (
    sfunc = sum_product_fn,
    stype = int, 
    initcond = 0
);

SELECT 
    sum(i) AS one,     
    sum_product(i, 2) AS double,
    sum_product(i,3) AS triple
FROM generate_series(1,3) i;

ROLLBACK;      

那样会给你一个类似这样的东西:
 one | double | triple 
-----+--------+--------
   6 |     12 |     18

3
这可以通过使用ntile窗口函数来实现。
-- To calculate flexible quantile ranges in postgresql, for example to calculate n equal 
-- frequency buckets for your data for use in a visualisation (such as binning for a 
-- choropleth map), you can use the following SQL:

-- this functions returns 6 equal frequency bucket ranges for my_column.
SELECT ntile, avg(my_column) AS avgAmount, max(my_column) AS maxAmount, min(my_column) AS     minAmount 
FROM (SELECT my_column, ntile(6) OVER (ORDER BY my_column) AS ntile FROM my_table) x
GROUP BY ntile ORDER BY ntile

您可以在http://database-programmer.blogspot.com/2010/11/really-cool-ntile-window-function.html找到更多关于ntile()函数和窗口函数的信息。

因为这个回答虽然对计算四分位数范围很有用,但问题实际上是关于创建聚合函数的。所以被踩是可以理解的。 - David Wolever

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接