title: Missing FROM-clause entry for a table
body: <p>I wrote the following SQL statement to get data from two tables <code>gendata</code> &amp; <code>TrainingMatrix</code>:</p>
  
  <pre><code>SELECT * FROM (SELECT DISTINCT ON ("TrainingMatrix".payroll, "TrainingName", "Institute")"gendata"."Employee Name","gendata"."Position", "gendata"."Department",  "TrainingMatrix".* 
  FROM "TrainingMatrix" JOIN "gendata" ON "TrainingMatrix".payroll = "gendata".payroll 
  ORDER  BY payroll, "TrainingName", "Institute" ,"TrainingDate" DESC NULLS LAST) AS foo;
  </code></pre>
  
  <p>It works fine, but I need to filter the records more by:</p>
  
  <pre><code>WHERE "TrainingMatrix"."ExpiryDate" - current_date &lt;= 0 
  AND  EXTRACT(YEAR FROM  "TrainingMatrix"."ExpiryDate") = EXTRACT(YEAR FROM current_date);
  </code></pre>
  
  <p>So, the orginal SQL statement will be:</p>
  
  <pre><code>SELECT * FROM (SELECT DISTINCT ON ("TrainingMatrix".payroll, "TrainingName", "Institute")"gendata"."Employee Name","gendata"."Position", "gendata"."Department",  "TrainingMatrix".* 
  FROM "TrainingMatrix" JOIN "gendata" ON "TrainingMatrix".payroll = "gendata".payroll 
  ORDER  BY payroll, "TrainingName", "Institute" ,"TrainingDate" DESC NULLS LAST) AS foo WHERE "TrainingMatrix"."ExpiryDate" - current_date &lt;= 0 
  AND  EXTRACT(YEAR FROM  "TrainingMatrix"."ExpiryDate") = EXTRACT(YEAR FROM current_date);
  </code></pre>
  
  <p>But I got this error:</p>
  
  <blockquote>
    <p>ERROR:  missing FROM-clause entry for table "TrainingMatrix" LINE 3:
    ...te" ,"TrainingDate" DESC NULLS LAST) AS foo WHERE "TrainingM...</p>
  </blockquote>
  
  <p>I am using PostgreSQL. Any advise guys?</p>