學習分析函式LAG以後,馬上學以致用 幫一網友解決問題.

cosio發表於2008-07-22
QUOTE:
原帖由 lypch 於 2008-7-12 11:28 發表 學習分析函式LAG以後,馬上學以致用 幫一網友解決問題.screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.style.cursor='hand'; this.alt='Click here to open new windownCTRL+Mouse wheel to zoom in/out';}" onclick="if(!this.resized) {return true;} else {window.open(this.src);}" src="http://www.itpub.net/images/common/back.gif" onload="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.alt='Click here to open new windownCTRL+Mouse wheel to zoom in/out';}" border="0" />
LEVEL Parent Child Parent Qty Child Qty
1 A B 1 3
2 B C 2 3
3 C D 5 6
4 D E 1 2
1 A Z 1 3

A是成品
B,C,D是半成品
E,Z是原材料

從上面一個比例關係可以計算出,做一個A最終需要10.8個E和3個Z,
也就是能看到下面的結果
Parent Child QTY
A E 10.8
A Z 3

我想知道有沒有什麼辦法透過一個SQL語句來實現這個功能。

請大家幫忙想象辦法。

搭測試環境:
create table T_T
(
T0 int
,parent varchar2(2)
,chile varchar2(2)
,parentQty int
,childQty int
)
insert into T_T values(1,'A','B',1,3);
insert into T_T values(2,'B','C',2,3);
insert into T_T values(3,'C','D',5,6);
insert into T_T values(4,'D','E',1,2);
insert into T_T values(1,'A','Z',1,3);
insert into T_T values(1,'H','I',1,3);
insert into T_T values(2,'I','J',1,3);
insert into T_T values(3,'G','H',1,3);
insert into T_T values(1,'L','M',1,2);
insert into T_T values(2,'M','N',1,9);
commit;


SQL:應用lag分析函式:
select aa.a,aa.c,aa.d,bb.h*decode(bb.i,0,1,bb.i)*decode(bb.j,0,1,bb.j)*decode(bb.k,0,1,bb.k) FROM
(
select B,min(parent) c,max(chile) d,A from(
select T0,parent,chile,
SUM(p) over(PARTITION BY A ORDER BY parent) B,A
FROM (
select T0,parent,chile,lag(chile) over(partition by a order by parent) C, (case when lag(chile) over(partition by a order by parent)=parent then 0 else 1 end ) P,B,A
from
(select T0,parent,chile,(case ASCII (chile)-ASCII (parent) when 1 then 1 else 2 end) A,childqty/parentqty B from t_t
order by parent)))
group by B,A)
AA
LEFT OUTER JOIN
(select A,C,sum(case T0 when 1 then B else 0 end) h,
sum(case T0 when 2 then B else 0 end) i,
sum(case T0 when 3 then B else 0 end) j,
sum(case T0 when 4 then B else 0 end) k
from(
select T0,parent,chile,B,
SUM(p) over(PARTITION BY A ORDER BY parent) C,A
FROM (
select T0,parent,chile,lag(chile) over(partition by a order by parent) C, (case when lag(chile) over(partition by a order by parent)=parent then 0 else 1 end ) P,B,A
from
(select T0,parent,chile,(case ASCII (chile)-ASCII (parent) when 1 then 1 else 2 end) A,childqty/parentqty B from t_t
order by parent)))
group by a,C) BB On aa.a||aa.b=bb.a||bb.c

BEFORE:
1 1 A B 1 3
2 1 A Z 1 3
3 2 B C 2 3
4 3 C D 5 6
5 4 D E 1 2
6 3 G H 1 3
7 1 H I 1 3
8 2 I J 1 3
9 1 L M 1 2
10 2 M N 1 9


RESULT:
1 1 A E 10.8
2 1 G J 27
3 1 L N 18
4 2 A Z 3[@more@]

但是還有一種情況,以上沒有辦法解決

如果多條資料為:

A F 1 3

抓出來的資料就會問題,這個BUG日後在想想看看有更好的解決辦法沒!

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/101162/viewspace-1007635/,如需轉載,請註明出處,否則將追究法律責任。

相關文章