在子查询中使用查询结果

时间:2012-05-29 17:10:24

标签: sql subquery teradata

我在查询时遇到问题。我已经阅读了很多东西,但尚未找到解决方案。问题在于子查询 - 它真的不喜欢它。有人可以帮助我让这个工作吗?

第一个表表示Work Performed表,第二个表表示Employee Information。我基本上试图使用'position_reports_to'字段获取员工的主管名称,该字段是HR代码。顺便说一句,这是在Teradata。

谢谢!

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

2 个答案:

答案 0 :(得分:3)

您可以尝试使用其他LEFT JOIN代替子查询:

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

答案 1 :(得分:1)

您在WHERE SID = T2.position_nbr中引用了T2,但不清楚要使用哪个T2。它可以是主FROM子句或子查询中的那个。由于存在歧义,查询将无法编译。

为了使其正常工作,您需要为其中一个T2添加别名

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
      ....

然而,当bfavaretto's answer显示您可以再次加入同一个表时,无论如何通常表现更好。

相关问题