|
PostgreSQL: Advanced SQL: User defined aggregates
- Aggregate: accumulate into a single representation
- Examples: count(), sum(), avg()
- Define your own aggregates with PostgreSQL:
01 CREATE AGGREGATE name (
02 BASETYPE = input_data_type,
03 SFUNC = sfunc,
04 STYPE = state_data_type
05 [ , FINALFUNC = ffunc ]
06 [ , INITCOND = initial_condition ]
07 )
- BASETYPE = data type which we are working with
- SFUNC = function to read in data - called for each iteration with state data and current datum
- STYPE = data type of state data
- FINALFUNC = function to output final aggregate
- INITCOND = initial state
- Example: aggregate data into an array (from Section 33.9, PostgreSQL manual)
01 CREATE AGGREGATE array_accum (
02 sfunc = array_append,
03 basetype = anyelement,
04 stype = anyarray,
05 initcond = '{}'
06 );
SELECT attrelid::regclass, array_accum(attname)
FROM pg_attribute
WHERE attnum > 0 AND attrelid = 'pg_user'::regclass
GROUP BY attrelid;
pg_user | {usename,usesysid,usecreatedb,usesuper,usecatupd,passwd,valuntil,useconfig}
(1 row)
Page 26
|