首页 > 解决方案 > 尝试在选择查询中命名列时出错

问题描述

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

我以前从未遇到过它,因为我认为我从未尝试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

这是在 SQL Fiddle 中设置的示例

标签: postgresqlpostgresql-9.6postgresql-10

解决方案


推荐阅读