Oracle相关子查询

时间:2019-02-21 07:59:30

标签: sql oracle subquery

我有一个包含字段的表:

USER_ID
MANAGER_USER_ID
COST_CENTER

我需要查询所有这些数据,但是COST_CENTER应该来自经理,所以我做到了:

select USER_ID, COST_CENTER, MANAGER_USER_ID
from EMDB e
where COST_CENTER in (
    select COST_CENTER
    from EMDB e2
    where e2.USER_ID = e.MANAGER_USER_ID
    );

样本数据:

USER_ID    MANAGER_USER_ID    COST_CENTER
user1      user3              employeeCostCenter1
user2      user3              employeeCostCenter1
user3      manager3           employeeCostCenter2  <-- this is manager

Sample output:
USER_ID    MANAGER_USER_ID    COST_CENTER
user1      user3              employeeCostCenter2  
user1      user3              employeeCostCenter2  
user3      manager3           costCenterOfManager3

但是这不起作用(不返回任何内容)。 有什么建议吗?

3 个答案:

答案 0 :(得分:1)

尝试一下:

select e.USER_ID,
       e.MANAGER_USER_ID
       e2.COST_CENTER             
    from EMDB e
      inner join EMDB e2 on e2.USER_ID = e.MANAGER_USER_ID

答案 1 :(得分:1)

您可以使用此:

SELECT e.user_id, e.manager_user_id, e2.cost_center
FROM emdb e
INNER JOIN emdb e2
ON e2.user_id = e.manager_user_id;

答案 2 :(得分:0)

以下是将子查询放入select子句的方法:

select 
  user_id, 
  manager_user_id,
  (select cost_center from emdb m where m.user_id = e.manager_user_id) as cost_center
from emdb e
order by user_id;