我在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;
Run Code Online (Sandbox Code Playgroud)
在PostgreSQL类似的代码中返回错误:
列total_1和total_2不存在.
基于
对横向列别名引用的支持使您能够编写查询,而无需在 SELECT 列表中重复相同的表达式。例如,您可以定义别名“probability”并在同一 select 语句中使用它:
Run Code Online (Sandbox Code Playgroud)select clicks / impressions as probability, round(100 * probability, 1) as percentage from raw_data;
这与以下内容基本相同:
select 1 AS col
,col + 1 AS col2;
Run Code Online (Sandbox Code Playgroud)
大多数 SQL RDBMS 都会返回错误:Unknown column 'col' in 'field list'
它看起来是一个有趣的语言扩展,但有一个警告。如果我有一个不确定的函数怎么办:
select RAND() AS col
,col + 1 AS col2
-- if RAND() returns 0.5 then I would expect
-- 0.5 and 1.5
-- I get: 0.3 and 1.7
-- it means that the query …Run Code Online (Sandbox Code Playgroud)