.\" XXX standard disclaimer belongs here....
.\" $Header: /private/postgres/ref/postquel/RCS/defineaggregate,v 1.11 1992/07/14 05:54:17 ptong Exp $
.SP "DEFINE AGGREGATE" COMMANDS 6/14/90
.XA 2 "Define Aggregate"
.uh NAME
.lp
define aggregate \*- define a new aggregate
.uh SYNOPSIS
.lp
.(l
\fBdefine aggregate\fR agg-name [\fBas\fR]
	\fB(\fR\fBsfunc1\fR \fB=\fR state-transition-function1,
	 \fBsfunc2\fR \fB=\fR state-transition-func2,
	 \fBfinalfunc\fR \fB=\fR final-function,
	 \fBinitcond1\fR \fB=\fR initial-condition1,
	 \fBinitcond2\fR \fB=\fR initial-condition2 \fB)\fR
.)l
.uh DESCRIPTION
.lp
An aggregate requires three functions, two
.i "state transition"
functions, X1 and X2:
.(l
X1( internal-state1, next-data_item ) ---> next-internal-state1
X2( internal-state2 ) ---> next-internal-state2
.)l
.lp
and a
.b "final calculation"
function, F:
.(l
F(internal-state1, internal-state2) ---> aggregate-value
.)l
.lp
These functions are required to have the following three properties:
.np
The return type of each state-transition-function and the arguments
of the final-calculation-function must be the same type (\fIt\fP).
.np
The return type of the final-calculation-function must be a \*(PP base
type.
.np
The first argument to state-transition-function1 must be of type \fIt\fP,
while the second argument must match the data type of the object
being aggregated.
.lp
Aggregates also require two initial conditions, one for each transition 
function.
.uh EXAMPLE
.lp
The
.i average
aggregate would consist of two state
transition functions, a summer and an incrementer.  These would
hold the internal state of the aggregate through a 
running sum and and the number of values seen so far.
It might accept a new employee salary,
increment the count, and add the new salary to
produce the next state.  The state transition functions must be
passed correct initialization values.  The final calculation 
then divides the sum by the count to produce the final
answer.
.lp
.ft C
/* Define an aggregate for int4average */
.ft
.lp
.ft C
define aggregate avg (sfunc1 = int4add, sfunc2 = int4inc
     finalfunc = int4div, initcond1 = "0", initcond2 = "0")
.fn
