I've been trying to wrap my head around creating aggregates in PostgreSQL (either 8.4 or 9.1) that accept one or more option parameters.
An example would be creating a PL/R
extension to compute the p-th quantile, with 0 <= p <= 1
. This would look something like quantile(x,p)
, and as part of a query:
select category,quantile(x,0.25)
from TABLE
group by category
order by category;
Where TABLE (category:text, x:float)
.
Suggestions?
Hopefully this example will help. You need a function that takes (accumulator, aggregate-arguments) and returns the new accumulator value. Play around with the code below and that should give you a feel for how it all fits together.
That should give you something like:
This can be achieved with the ntile windowing function
You can find more on the ntile() function and windowing at http://database-programmer.blogspot.com/2010/11/really-cool-ntile-window-function.html