具有多个参数的PostgreSQL聚合

时间:2011-12-16 05:00:48

标签: postgresql aggregates

我一直试图在PostgreSQL(8.4或9.1)中创建接受一个或多个选项参数的聚合。

一个示例是使用PL/R创建0 <= p <= 1扩展来计算第p个分位数。这看起来像quantile(x,p),并且作为查询的一部分:

select category,quantile(x,0.25)
from TABLE
group by category
order by category;

TABLE (category:text, x:float)

建议?

2 个答案:

答案 0 :(得分:5)

希望这个例子会有所帮助。您需要一个带(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;      

那应该给你一些:

 one | double | triple 
-----+--------+--------
   6 |     12 |     18

答案 1 :(得分: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()函数和窗口的更多信息