PostgreSQL - 错误:列不存在 SQL 状态:42703

问题描述 投票:0回答:3

我正在尝试进行队列分析,并根据承租人的第一个租赁年份(=承租人第一次租赁的年份)比较平均租赁次数。基本上,我问的问题是:我们是否会保留第一年租金为 2013 年的租户,而不是第一年为 2015 年的租户?

这是我的代码:

SELECT renter_id, 
       Min(Date_part('year', created_at)) AS first_rental_year, 
       ( Count(trip_finish) )             AS number_of_trips 
FROM   bookings 
WHERE  state IN ( 'approved', 'aboard', 'ashore', 'concluded', 'disputed' ) 
  AND  first_rental_year = 2013 
GROUP  BY 1 
ORDER  BY 1; 

我收到的错误消息是:

ERROR:  column "first_rental_year" does not exist
LINE 6: ... 'aboard', 'ashore', 'concluded', 'disputed') AND first_rent...
                                                             ^

********** Error **********

ERROR: column "first_rental_year" does not exist
SQL state: 42703
Character: 208

非常感谢任何帮助。

sql postgresql column-alias
3个回答
6
投票
SELECT renter_id,
       Count(trip_finish) AS number_of_trips 
FROM (
        SELECT renter_id, 
               trip_finish,
               Min(Date_part('year', created_at)) AS first_rental_year
        FROM   bookings 
        WHERE  state IN ( 'approved', 'aboard', 'ashore', 'concluded', 'disputed' ) 
     ) T
WHERE first_rental_year = 2013  
GROUP  BY renter_id
ORDER  BY renter_id ; 

4
投票

错误:

SQL 错误 [42703]:错误:列 XYZ 不存在

检查列字段周围是否有 双引号

坏:

update public."AppTime" t Set "CustomTask"= 'XYZ' where  t.SharedAppId = 12890;

好:

“SharedAppId”两边加双引号

update public."AppTime" t Set "CustomTask"= 'XYZ' where  t."SharedAppId" = 12890;

如果您创建的表不带引号,则在查询时不应使用引号,反之亦然。 手册中对此进行了解释:“如果您想编写可移植应用程序,建议您始终引用特定名称或从不引用它”


0
投票

回复有点晚了,但我遇到了这个问题,不得不花很多时间解决简单的问题以节省您的时间,这就是解决方案

在 PostgreSQL 中,如果列名是使用大写或混合大小写字母创建的或包含特殊字符,则在 SQL 查询中引用它时必须使用双引号括起来。默认情况下,PostgreSQL 将所有未加引号的标识符转换为小写,这意味着名为 Patient_id (大小写混合)的列需要被引用为“Patient_id”。

要点: 如果该列全部以小写形式创建,则不需要双引号(例如,病人 ID)。 如果该列是使用大写或混合大小写创建的,则必须使用双引号(例如“Patient_id”)。

© www.soinside.com 2019 - 2024. All rights reserved.