2011-12-16 32 views
6

我一直試圖圍繞在PostgreSQL(8.4或9.1)中創建接受一個或多個選項參數的聚集。PostgreSQL與多個參數聚合

一個例子是創建一個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)

對此提出建議?

回答

5

希望這個例子會有所幫助。您需要一個函數(累加器,聚合參數)並返回新的累加器值。玩下面的代碼,這應該讓你感覺如何融合在一起。

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 

你可以找到更多關於NTILE()函數和窗口的實現http://database-programmer.blogspot.com/2010/11/really-cool-ntile-window-function.html

+0

太棒了!謝謝! – alfonx 2012-01-23 23:15:16