Postgres中的动态计算公式
我想知道是否有可能在 Postgres 中创建类似命名计算的东西?假设我有一个表:
create table foo (
bar smallint,
baz smallint
)
我可以运行 select (bar / baz) * 100 from foo;
来获取结果,但我想要一个公式(伪代码):avg_foo ::= (bar/baz)*100
然后执行 select avg_foo from foo;
以获得相同的结果。理想情况下,我希望有一个包含计算的单独表:
create table calculations (
name varchar,
formula varchar
)
以便我可以动态创建计算并在选择中使用它们,如下所示:
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?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在plpgsql中编写一个元组返回函数,并从内部调用所需的函数。
Write a tuple returning function in plpgsql, and call the required functions from within.