Chr*_*ong 6 postgresql aggregates
我一直试图在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;
Run Code Online (Sandbox Code Playgroud)
哪里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,
sum_product(i,3) AS triple
FROM generate_series(1,3) i;
ROLLBACK;
Run Code Online (Sandbox Code Playgroud)
这应该给你这样的东西:
one | double | triple
-----+--------+--------
6 | 12 | 18
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3734 次 |
| 最近记录: |