我一直试图在Postgresql(8.4或9.1)中创建接受一个或多个选项参数的聚合.
一个例子是创建PL / R扩展来计算第p个分位数,其中0 <= p <= 1.这看起来像分位数(x,p),并且作为查询的一部分:
- select category,quantile(x,0.25)
- from TABLE
- group by category
- order by category;
TABLE(category:text,x:float).
建议?
希望这个例子会有所帮助.您需要一个带(accumulator,aggregate-arguments)并返回新累加器值的函数.玩下面的代码,这应该让你感觉它们是如何组合在一起的.
- 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,3) AS triple
- FROM generate_series(1,3) i;
- ROLLBACK;
这应该给你这样的东西:
- one | double | triple
- -----+--------+--------
- 6 | 12 | 18