Oracle 中Connect By 子句對在關系表上表現層次關系提供了方便
使用Connect by 子句需要在表中定義兩個字段
例如我們作一張資產負債表
數據來源
資 產 期末余額 負債及所有者權益 期末余額
流動資產
現金
存放中央銀行款項
存放同業款項
短期貸款
其他流動資產
長期資產
中長期貸款
減
固定資產淨值
其他長期資產
無形
其中
資產總計
Create table balance_sheet (BS_ID INTEGER
BS_ID 項目代碼 BS_PID 項目父代碼 BS_Name 項目名稱 BS_VALUE 數據列
插入測試數據
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
insert into balance_sheet values(
commit;
顯示全部數據
select bs_name
connect by prior bs_id = bs_pid
start with bs_pid =

顯示一個節點的數據
select bs_name
connect by prior bs_id = bs_pid
start with bs_pid =
其中connect by 定義父子連接關系
start with 定義開始節點

(流動資產節點數據)
顯示層次結構
select (case when level =
when level =
end ) bs_name
connect by prior bs_id = bs_pid
start with bs_pid =
其中引用了level字段

(根據層次來實現縮進風格)
層次內排序
select (case when level =
when level =
end ) bs_name
connect by prior bs_id = bs_pid
start with bs_id =
ORDER SIBLINGS BY bs_value desc

select
ltrim(sys_connect_by_path( BS_Name
(case when level =
when level =
end ) bs_name
from balance_sheet
connect by prior bs_id = bs_pid
start with bs_pid =

層次計算
這裡層次計算是指根據父子節點關系進行匯總
但是在財務報表父指標
例如
長期資產 = 中長期貸款 – 貸款呆賬准備 +固定資產淨值 +其他長期資產
為了實現這種情況
這樣 父節點 = SUM(子節點 * Direction)
SELECT
SUBSTR (PATH
sum(bs_value * bs_dir)
FROM (SELECT BS_ID
bs_value
FROM balance_sheet
CONNECT BY PRIOR bs_id = bs_pid
START WITH bs_pid =
group by SUBSTR (PATH

竟然有意外的收獲
數據的最後一行是對所有原表第一層節點的疊加
BS_LParID
From:http://tw.wingwit.com/Article/program/Oracle/201311/18351.html