你可以从技术上讲,使用execute
语句进行PLPGSQL功能:
return query
execute $x$
select id, $x$ || quote_ident(agg_func) || $x$(col)::numeric as agg
from bar
$x$;
(见下面一个适当的例子)。问题是,这将意味着在每次调用时解析/计划您的查询。
有时,更好的选择是创建一个创建各种所需功能的函数。就像这样:
create or replace function generate_agg_functions(_table regclass) returns void as $$
declare
_agg_type text[] = '{sum, avg}';
_ret_type regtype[] = '{numeric, numeric}';
rec record;
begin
for rec in select _agg_type[i] as agg_type, _ret_type[i] as ret_type
from generate_subscripts(_agg_type, 1) i
loop
execute $x$
create or replace function $x$ || quote_ident(_table || '_' || rec.agg_func) || $x$()
returns table (id int, $x$ || quote_ident(rec.agg_type) || ' ' || ret_type || $x$)
$def$
begin
return query
select id,
$x$ || quote_ident(rec.agg_type) || $x$(col)::$x$ || rec.ret_type || $x$
as $x$ || quote_ident(rec.agg_type) || $x$
from $x$ || _table || $x$;
end;
$def$ language plpgsql stable;
$x$;
end loop;
end;
$$ language plpgsql;
写起来有点棘手,但最终不会重复代码而不影响单个聚合的性能。
哇!我现在感觉像我还有很多东西要学习postgresql。也许现在如果aggr_type == .../else不再是一个糟糕的选项。感谢您的帮助队友! :-) – ssc 2011-05-30 13:13:28