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)

建议?

4

2 回答 2

7

希望这个例子会有所帮助。您需要一个接受(累加器,聚合参数)并返回新累加器值的函数。玩弄下面的代码,这应该让您了解它们是如何组合在一起的。

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
于 2011-12-16T14:18:19.270 回答
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() 函数和窗口的信息

于 2012-01-09T15:40:53.173 回答