简体   繁体   English

在子查询中使用查询结果

[英]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. 我基本上是在尝试使用人力资源代码“ position_reports_to”字段来获取员工的主管名称。 By the way, this is in Teradata. 顺便说一下,这是在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

You can try another LEFT JOIN instead of the subquery: 您可以尝试使用另一个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

You are referencing T2 in WHERE SID = T2.position_nbr but its not clear which T2 to be used. 您在WHERE SID = T2.position_nbr中引用T2,但不清楚使用哪个T2。 It could be the one in the main FROM clause or in the Subquery. 它可以是主FROM子句中或子查询中的那个。 Since there's ambiguity the query won't compile. 由于存在歧义,因此无法编译查询。

In order for this to work you'd need to alias one of the T2s 为了使其正常工作,您需要对T2之一进行别名

Eg 例如

 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. 但是,正如bfavaretto的答案显示的那样,您可以再次连接到同一张表,通常它的性能通常更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM