在下面提供的解決方案(包括輸入數據作爲因式分解的子查詢),第一我展示如何使用unpivot
和附加操作正常化tab1
(結果是因子分解子查詢n
爲「n
ormalized」 )。然後,如果你有正常形式的數據,則可以通過直接應用我的代碼底部顯示的標準分層查詢來獲得輸出結果。
with
tab1 (key, L1, L2, L3) as (
select 'A', 'A', null, null from dual union all
select 'B', 'A', 'B' , null from dual union all
select 'C', 'A', 'B' , 'C' from dual union all
select 'D', 'A', 'B' , 'D' from dual
),
tab2 (key, TC) as (
select 'A', 10 from dual union all
select 'B', 11 from dual union all
select 'C', 6 from dual union all
select 'D', 12 from dual union all
select 'X', 11 from dual
),
unpiv (key, l, ancestor) as (
select key, to_number(substr(lv, 2)), ancestor from tab1
unpivot (ancestor for lv in (L1, L2, L3))
),
d (key, depth) as (
select key, max(l)
from unpiv
group by key
),
n (child, parent, TC) as (
select d.key, u.ancestor, tab2.TC
from unpiv u
right outer join d
on u.key = d.key and u.l = d.depth - 1
left outer join tab2
on d.key = tab2.key
)
SELECT key, sum(TC) as sum_TC
from (
select connect_by_root child as key, TC
from n
connect by prior child = parent
)
group by key
order by key;
一路上,在unpiv
,我已經把所有的父子關係,所以我可以直接加入與tab2
上unpiv.key = tab2.key
和ancestor
(類似於MT0的解決方案)總結TC
分組。相反,我想演示兩個單獨的步驟:(1)規範化tab1
和(2)在規範化表上使用分層查詢是多麼容易。
輸出:
KEY SUM_TC
--- ----------
A 39
B 29
C 6
D 12
這裏是一個偉大的地方開始。 http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/ –
請爲此數據提供所需的輸出,因爲它不清楚什麼你的意思是*每個級別的總和*。我想至少有3種解釋。 – trincot
添加到trincot的評論 - 不要只提供所需的輸出,用英文解釋(無代碼!)如何輸出。 – mathguy