sql - PostgreSQL:在同一查询中使用计算列

标签 sql postgresql calculated-columns column-alias

我在 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/

相关文章:

sql - 通过旋转将 Presto 列转换为行

mysql - 返回包含 rows 的行数

sql - 给定两个数组如何获取不在两个数组中的项目?

sql - 在 Rails 中执行 destroy_all 的更有效方法?

arrays - Postgres jsonb 选择特定的数组字段

sql - 几个查询中出现相同的SQL错误

sql - 替代UNION子句

sql - 如何通过 "nodes"命令在 SQL XML 查询中使用命名空间?

python - 如何根据另一列中的重复值在一列中添加行,并最终在 python 中保留第一行?

sql - 为什么 Oracle 不识别存储的生成列定义?