7

私は、PostgreSQL (8.4 または 9.1) で 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

この例が役に立てば幸いです。(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
于 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

ntile()関数とウィンドウ処理の詳細については、http: //database-programmer.blogspot.com/2010/11/really-cool-ntile-window-function.htmlを参照してください。

于 2012-01-09T15:40:53.173 に答える