你可以從技術上講,使用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