我不确定获得所需结果的最佳方法是什么。在 oracle 10g 数据库中,我试图查询所有用户并为每行生成一个计算字段,如果他们的主管类型是 U。如果不是,我需要沿着树向上走,直到找到一个. 此查询可能需要递归多个级别。
所以对于这样的 Employee 表:
Employee Table
+-------+----------+--------------+---------------+
| empno | empgroup | user | supervisor_no |
+-------+----------+--------------+---------------+
| 1 | E | Joe Schmo | 4 |
| 2 | E | Mark Marin | 3 |
| 3 | U | Reed Patter | 7 |
| 4 | E | Martin Price | 7 |
| 7 | U | Mary Wengert | |
+-------+----------+--------------+---------------+
我希望看到这样的结果,其中 manager_no 将是计算字段
Results
+-------+----------+--------------+---------------+------------+
| empno | empgroup | user | supervisor_no | Manager_No |
+-------+----------+--------------+---------------+------------+
| 1 | E | Joe Schmo | 4 | 7 |
| 2 | E | Mark Marin | 3 | 3 |
| 3 | U | Reed Patter | 7 | 7 |
| 4 | E | Martin Price | 7 | 7 |
| 7 | U | Mary Wengert | | |
+-------+----------+--------------+---------------+------------+
好的,所以有人问我尝试了什么。我并不是说这是必须这样做的方式,所以如果有人有更好的建议,我会全力以赴,但这就是我想要实现的目标。
我设想了两个部分。获得我所有结果的主要查询
select em.empno, em.empgroup, em.user, em.supervisor, (my subquery) as manager_no
from employee em
查询:
select * from employee em
connect by prior supervisor_no = empno
start with empno = 1
[结果][2]:
| EMPNO | EMPGROUP | USERNAME | SUPERVISOR_NO |
---------------------------------------------------
| 1 | E | Joe Schmo | 4 |
| 4 | E | Martin Price | 7 |
| 7 | U | Mary Wengert | (null) |
好的,我找到了一种过滤可能有效的组的方法,但不确定这是否是最有效的路线。
SELECT empno FROM (
SELECT empno FROM employee em
CONNECT BY PRIOR supervisor_no = empno
START WITH empno = 1
order by level) d
WHERE d.empgroup = 'U' and rownum =1
如果有帮助,我还创建了一个小提琴。 http://www.sqlfiddle.com/#!4/c8805/4