ORACLE有条件地选择多行

时间:2018-12-04 11:04:40

标签: sql oracle select

有这样的表格:

CREATE TABLE Emp
    (manager varchar(14), sub varchar(14))
;

INSERT ALL 
    INTO Emp (manager, sub)
         VALUES ('boss', 'john')
    INTO Emp (manager, sub)
         VALUES ('boss', 'eric')
    INTO Emp (manager, sub)
         VALUES ('boss', 'anna')
    INTO Emp (manager, sub)
         VALUES ('boss1', 'boss')
    INTO Emp (manager, sub)
         VALUES ('boss1', 'kris')
    INTO Emp (manager, sub)
         VALUES ('boss1', 'dave')
SELECT * FROM dual
;

,并给了一个雇员(子)的名字,我想返回的名字如下:

  • 如果员工是经理,请让自己和他的团队
  • 如果员工不是经理,请找他的经理和他的团队

仅当员工是经理时,此选项才有效:

SELECT sub FROM Emp
WHERE manager = 'boss' OR sub ='boss'
;

因此,基本上,如果给定的雇员是“约翰”或“老板”,则数据应如下所示:

john
eric
anna
boss

2 个答案:

答案 0 :(得分:1)

获取所有经理团队并向其中添加经理:

with man as (
 select manager as sub from emp where sub = 'john'
 )
select Emp.sub from Emp,man where manager = man.sub    
union all
select sub from man

如果您将老板确定为经理价值而不是“老板”,那么您可以为老板/子组建团队

with man as (
 select manager as sub from emp where sub = 'john'
 )
select Emp.sub from Emp,man where manager = decode(Emp.manager,'boss',man.sub, Emp.sub)    
union all
select sub from man

编辑不带别名的SQL

with man as (
 select manager from emp where sub = 'john'
 )
select Emp.sub from Emp,man where manager = decode(Emp.manager,'boss',man.manager, Emp.sub)    
union all
select manager from man

编辑:删除上级团队:

with man as (
 select manager,sub from emp where sub = 'john'
 )
select Emp.sub from Emp,man where Emp.manager = decode(Emp.manager,'boss',Emp.manager, Emp.sub)    
union all
select manager from man where   sub <>'boss'
union all
select sub from man where   manager <>'boss'

答案 1 :(得分:1)

  select manager from emp where sub in (:name) and manager in (select sub from emp) 
 union
select sub from emp where manager in (select manager from emp where sub=:name and sub=manager) 
 union 
select sub from emp where manager in (select :name from emp )
 union
select sub from emp where manager in (select manager from emp where sub=:name and manager in (select sub from emp))
 union
select :name from dual;

这里的名称是绑定变量。我和约翰和老板都尝试过。它为我工作。它给了我预期的数据。