我在 postgres 中使用计算列时遇到问题。下面给出了在 SQL 中工作的类似代码,是否可以在 PostgreSQL
中重新创建它?
select cost_1, quantity_1, cost_2, quantity_2,
(cost_1 * quantity_1) as total_1,
(cost_2 * quantity_2) as total_2,
(calculated total_1 + calculated total_2) as total_3
from data;
在 PostgreSQL
中,类似的代码返回错误:
the column total_1 and total_2 do not exist.
最佳答案
您需要将 SELECT 语句包装到派生表中,以便能够访问列别名:
select cost1,
quantity_1,
cost_2,
quantity_2
total_1 + total_2 as total_3
from (
select cost_1,
quantity_1,
cost_2,
quantity_2,
(cost_1 * quantity_1) as total_1,
(cost_2 * quantity_2) as total_2
from data
) t
不会有任何性能损失。
(我真的很惊讶您的原始 SQL 语句完全在 DBMS 中运行)
关于sql - PostgreSQL:在同一查询中使用计算列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8840228/