cte中重复的列

时间:2014-05-18 13:56:56

标签: sql oracle common-table-expression

http://sqlfiddle.com/#!4/3fc99/1

我在以下ctc中需要帮助重复列。

with RSFC(EMPID,ENAME,MGRID,LVL,SAL) as(
  select EMPLOYEE_ID,EMPLOYEE_NAME,MANAGER_ID,0 as LVL,SALARY from COMPANY
  where MANAGER_ID is null
  union all
  select EMPLOYEE_ID,EMPLOYEE_NAME,MANAGER_ID,LVL+1,SALARY from RSFC R
  inner join COMPANY F
  on F.MANAGER_ID = R.EMPID
)
cycle SAL set IS_CYCLE to 'Y' default 'N'
select * from RSFC

结果

         EMPID ENAME                                                   MGRID        LVL        SAL IS_CYCLE
---------- -------------------------------------------------- ---------- ---------- ---------- --------
         1 FRED                                                                   0     100000 N        
         1 FRED                                                                   0     100000 N        
         2 BARNEY                                                      1          1      50000 N        
         2 BARNEY                                                      1          1      50000 N        
         3 WILMA                                                       1          1      50000 N        

1 个答案:

答案 0 :(得分:0)

问题是"弗雷德"数据中出现两次,ID相同。我建议将EmployeeId作为主键(因此是唯一的)。实际上,该表可能应该被称为Employees而不是Company

您只需获取不同的值即可修复查询:

with employees as (
      select distinct *
      from company
     ),
     RSFC(EMPID,ENAME,MGRID,LVL,SAL) as(
      select EMPLOYEE_ID,EMPLOYEE_NAME,MANAGER_ID,0 as LVL,SALARY
      from employees
      where MANAGER_ID is null
      union all
      select EMPLOYEE_ID,EMPLOYEE_NAME,MANAGER_ID,LVL+1,SALARY
      from RSFC R inner join
           employees F
           on F.MANAGER_ID = R.EMPID
     )
cycle SAL set IS_CYCLE to 'Y' default 'N'
select * from RSFC;