我有以下表格结构。我想从TAB2获得每个级别的总和。
TAB1将层次结构存储在级别列中。
softmax_w = tf.get_variable("softmax_w", [hidden_size, 1], )
softmax_b = tf.get_variable("softmax_b", [1])
init_op = tf.initialize_all_variables()
这是SQLFiddle链接:LINK TO FIDDLE
答案 0 :(得分:1)
Oracle设置
Create table TAB1 (pKey varchar2(10),level1 varchar2(10),level2 varchar2(10),level3 varchar2(10),level4 varchar2(10));
insert into TAB1(pKey,level1) values('A','A');
insert into TAB1(pKey,level1,level2) values('B','A','B');
insert into TAB1(pKey,level1,level2,level3) values('C','A','B','C');
insert into TAB1(pKey,level1,level2,level3) values('D','A','B','D');
Create table TAB2 (pKey varchar(10), tc integer);
insert into TAB2(pKey,tc) values('A',10);
insert into TAB2(pKey,tc) values('B',11);
insert into TAB2(pKey,tc) values('C',6);
insert into TAB2(pKey,tc) values('D',12);
insert into TAB2(pKey,tc) values('X',11);
<强>查询强>:
SELECT t2.pKey,
SUM( COALESCE( t4.TC, t2.tc ) ) AS tc
FROM tab2 t2
LEFT OUTER JOIN
tab1 t1
ON ( t2.pKey = t1.pKey )
LEFT OUTER JOIN
tab1 t3
ON ( t1.level1 = t3.level1
AND ( t1.level2 IS NULL OR t1.level2 = t3.level2 )
AND ( t1.level3 IS NULL OR t1.level3 = t3.level3 )
AND ( t1.level4 IS NULL OR t1.level4 = t3.level4 ) )
LEFT OUTER JOIN
tab2 t4
ON ( t3.pKey = t4.pKey )
GROUP BY t2.pKey;
<强>输出强>:
PKEY TC
---------- ----------
D 12
A 39
B 29
C 6
X 11
答案 1 :(得分:1)
在下面提供的解决方案中(包括输入数据作为因子子查询),首先我展示如何使用unpivot
和其他操作来规范化tab1
(结果是因子子查询{{1} } for&#34; n
ormalized&#34;)。然后,如果你有正常形式的数据,可以通过直接应用标准分层查询获得输出,如我的代码底部所示。
n
在此过程中,在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
按TC
分组(类似于MT0&#39;解决方案)。相反,我想展示两个单独的步骤:(1)规范化ancestor
和(2)在规范化表上使用分层查询是多么容易。
<强>输出强>:
tab1