Postgres SQL - 列不存在

Postgres SQL - Column does not exist

SELECT nmemail as order_email, 
       dtorder, 
       vlOrder, 
       cohorts.cohortdate 
FROM   factorderline 
       JOIN (SELECT nmemail as cohort_email, Min(dtorder) AS cohortDate FROM  factorderline GROUP  BY cohort_email limit 5) cohorts 
ON order_email= cohort_email limit 5; 

ERROR: column "order_email" does not exist

这个查询有什么问题?

问题很可能是在评估联接时尚未解析列别名的定义;请改用实际的列名:

SELECT nmemail as order_email, 
       dtorder, 
       vlOrder, 
       cohorts.cohortdate 
FROM   factorderline 
JOIN (
  SELECT nmemail as cohort_email, Min(dtorder) AS cohortDate 
  FROM  factorderline 
  GROUP BY cohort_email limit 5
) cohorts ON nmemail = cohort_email 
limit 5; 

此外,在使用 limit 时,您确实应该使用 order by 子句。

来自文档:

When using LIMIT, it is important to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query's rows.

问题是输出列名称不能用于联接。

来自the documentation

An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead.