尝试在选择查询中命名列时出错

时间:2018-12-18 02:08:55

标签: postgresql postgresql-9.6 postgresql-10

我尝试在工作中早些时候运行以下查询,但遇到了我不理解的错误。

我以前从未遇到过,因为我认为我从未尝试使用返回返回名为SELECT的列的聚合编写cost查询。

这是示例数据和架构

-- setup & sample data
CREATE TABLE test (cost NUMERIC(10,4));
INSERT INTO test VALUES (123), (234), (345);
-- query
SELECT SUM(cost) cost FROM test;
-- error message:
ERROR:  syntax error at or near "cost"
LINE 1: SELECT SUM(cost) cost FROM test;
                         ^

类似地,以下内容也返回相同的错误:

SELECT FIRST_VALUE(cost) OVER () cost FROM test;
-- error message:
ERROR:  syntax error at or near "cost"
LINE 1: SELECT FIRST_VALUE(cost) OVER () cost FROM test;
                                         ^
SELECT cost cost FROM test;
ERROR:  syntax error at or near "cost"
LINE 1: SELECT cost cost FROM test;
                    ^

但是,当我明确使用AS命名表达式时,没有任何问题:

示例(这些都可以正常工作):

SELECT cost AS cost FROM test;
SELECT FIRST_VALUE(cost) OVER () AS cost FROM test;
SELECT SUM(cost) AS cost FROM test;

我基本上给集合取了一个不同的名字,一切都很好,但是我很好奇为什么会这样?我想象发生了一些名称冲突,但是我不确定它与什么冲突。


这是我的PostgreSQL版本/平台信息,给出上述错误:

PostgreSQL 10.4, compiled by Visual C++ build 1800, 64-bit / Windows 10.

此外,我在以下系统(AWS RDS)上运行它,并得到了相同的错误

PostgreSQL 9.6.3 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9), 64-bit

Here is the example set up in SQL Fiddle

0 个答案:

没有答案