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

DBE*_*BE7 3 sql postgresql

我正在尝试进行队列分析,并根据承租人的第一个租赁年份(=承租人第一次租赁的年份)比较平均租金。基本上,我在问一个问题:我们是否保留第一年是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; 
Run Code Online (Sandbox Code Playgroud)

我收到的错误消息是:

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
Run Code Online (Sandbox Code Playgroud)

任何帮助深表感谢。

Jua*_*eza 5

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 ; 
Run Code Online (Sandbox Code Playgroud)

  • 问题是您不能在where上使用别名“ first_rental_year”,因为当时别名不存在。因此,您可以在子查询中创建别名,并在外部使用它。您还可以更改别名并使用函数`Min(Date_part('year',created_at))= 2013` (2认同)