Dynamic calculation formulas in Postgres
I'd like to know if there is a possibility to create something like named calculations in Postgres? Say, I have a table:
create table foo (
bar smallint,
baz smallint
)
I can run select (bar / baz) * 100 from foo;
to get my result, but I'd like to have a formula (pseudocode): avg_foo ::= (bar/baz)*100
and then do select avg_foo from foo;
to get the same result. Ideally, I'd like to have a separate table with calculations开发者_如何转开发:
create table calculations (
name varchar,
formula varchar
)
So that I could create calculations dynamically and use them in selects, like this:
insert into calculations (name, formula) values
('sum_bar_baz', 'bar+baz'),
('mult_bar_baz', 'bar*baz');
select sum_bar_baz, mult_bar_baz from foo;
How do I do this with Postgres?
Write a tuple returning function in plpgsql, and call the required functions from within.
精彩评论