NewbBill
NewbBill

Reputation: 5

Using Query Results in a Subquery

I am having trouble with this query. I have read quite a few things but have yet to find a solution. The problem is with the subquery- it really doesn't like it. Can someone help me get this to work?

The first table represents a Work Performed table and the second talbe shows Employee Information. I am basically trying to get a supervisor name for an employee using the 'position_reports_to' field which is an HR code. By the way, this is in Teradata.

Thanks!

select
t1.record_number,
T1.record_created_by,
T2.last_name,
T2.first_name,
T2.employee_no,
t2.position_number,
T2.position_reports_to as SUPID,
(select last_name from T2 where SID=T2.position_nbr) as SUP
from T1
left join T2 on T1.record_created_by=T2.employee_no
where
t1.record_create_date=current_date

Upvotes: 0

Views: 616

Answers (2)

Conrad Frix
Conrad Frix

Reputation: 52645

You are referencing T2 in WHERE SID = T2.position_nbr but its not clear which T2 to be used. It could be the one in the main FROM clause or in the Subquery. Since there's ambiguity the query won't compile.

In order for this to work you'd need to alias one of the T2s

E.g.

 SELECT
       .....
      (select last_name from T2 Sup where Sup.SID=T2.position_nbr) as SUP
 FROM  
     T1
     left join T2 on T1.record_created_by=T2.employee_no
      ....

However as bfavaretto's answer shows you can just join to the same table again, which usually performs better anyway.

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71918

You can try another LEFT JOIN instead of the subquery:

SELECT
   t1.record_number,
   T1.record_created_by,
   T2.last_name,
   T2.first_name,
   T2.employee_no,
   t2.position_number,
   T2.position_reports_to AS SUPID,
   sup.last_name AS sup_last_name
FROM T1
LEFT JOIN T2 ON T1.record_created_by=T2.employee_no
LEFT JOIN T2 sup ON sup.SID=T2.position_nbr
WHERE t1.record_create_date=current_date

Upvotes: 3

Related Questions