创建自定义函数或存储过程

时间:2014-02-20 21:02:32

标签: sql oracle plsql oracle11g oracle-sqldeveloper

我有一个Hierarchy表,其中包含Master_idSub_id

sub_id Master_id
2      1
3      2
4      1
5      3
6      7

我想创建一个迭代函数或存储过程(我不确定以前从未使用过它们)来创建一个列,它给我primary_master_Column(PMC)

sub_id Master_id PMC
2      1         1
3      2         1
4      1         1
5      3         1
6      7         7

2 个答案:

答案 0 :(得分:2)

select
  Master_id, sub_id, 
  max(PMC) keep(dense_rank first order by lev desc) as PMC
from
(
select 
  sub_id as PMC, level lev, 
  connect_by_root(Master_id) as Master_id,
  connect_by_root(sub_id) as sub_id
from your_table
connect by prior sub_id = Master_id
)
group by Master_id, sub_id

fiddle

答案 1 :(得分:2)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE test (sub_id, Master_id) AS
          SELECT 2,      1 FROM DUAL
UNION ALL SELECT 3,      2 FROM DUAL
UNION ALL SELECT 4,      1 FROM DUAL
UNION ALL SELECT 5,      3 FROM DUAL
UNION ALL SELECT 6,      7 FROM DUAL;

查询1

SELECT t.sub_id,
       t.master_id,
       CONNECT_BY_ROOT( t.master_id ) AS PMC
FROM   test t
       LEFT OUTER JOIN
       test x
       ON ( t.master_id = x.sub_id )
START WITH x.sub_id IS NULL
CONNECT BY PRIOR t.sub_id = t.master_id

<强> Results

| SUB_ID | MASTER_ID | PMC |
|--------|-----------|-----|
|      2 |         1 |   1 |
|      3 |         2 |   1 |
|      5 |         3 |   1 |
|      4 |         1 |   1 |
|      6 |         7 |   7 |

查询2

SELECT t.sub_id,
       t.master_id,
       CONNECT_BY_ROOT( t.master_id ) AS PMC
FROM   test t
START WITH NOT EXISTS ( SELECT 'x' FROM test x WHERE t.master_id = x.sub_id )
CONNECT BY PRIOR t.sub_id = t.master_id

<强> Results

| SUB_ID | MASTER_ID | PMC |
|--------|-----------|-----|
|      2 |         1 |   1 |
|      3 |         2 |   1 |
|      5 |         3 |   1 |
|      4 |         1 |   1 |
|      6 |         7 |   7 |