2016-05-12 80 views
0

我在進行層次結構查詢時遇到問題。層次結構SQL服務器加入兩個不同的表

我有MS SQL數據庫如下:

表A - 訂單與訂單代碼,物品,數量:有文章集的引用

OP | ART | QTY 

A | X |100 
B | Y |200 

表B,但文章可以製成其他物品,如果存在一個孩子的引用(可能需要去3級深):

ART | ART2 |QTY 

X | U | 20 
X | O | 10 
X | Z | 30 
Y | Q | 20 
Y | W | 15 
Y | E | 30 
U | Z | 10 

我想是這樣的:

A.OP |LEVEL| ART | B.ART2 |QTY 
A  | 2 | X | Z  |(100*20*10)=2000 
A  | 1 | X | O  |(100*10) =1000 
A  | 1 | X | Z  |(100*30) = 3000 
B  | 1 | Y | Q  |(200*20) = 4000 
B  | 1 | Y | W  |(200*15) = 3000 
B  | 1 | Y | E  |(200*30) = 6000 
B  | 1 | Y | Z  |(200*10) = 2000 

我已經做了一兩件事:

WITH X AS (
SELECT 
firstlvl.ART, 
1 AS LEVEL, 
firstlvl.ART2, 
firstlvl.QTY, 
QTY AS PARENTQTY 
FROM B AS firstlvl 
WHERE firstlvl.ART='X' 
UNION ALL 
SELECT secondlevel.ART, 
EL.LEVEL +1, 
secondlevel.BDT_MLC, 
secondlevel.ART2, 
secondlevel.QTY, 
EL.PARENTQTY AS PARENTQTY 
FROM B AS secondlevel 
INNER JOIN X AS EL 
ON secondlevel.ART = EL.ART2) 
SELECT * FROM X 

但現在我不知道如何加入量與表A也不如何運行此查詢第一表中的所有項目。

任何人都可以幫助我嗎?

非常感謝!

+0

爲了使響應者更容易,請讓SQL小提琴http://sqlfiddle.com/ – Alex

回答

0
with AllData as 
(select op as art, art as art2, qty from a 
union all 
    select * from b), 
Tree(RootLvl, Father, Child, qty, lvl) as (
select art, art, art2, qty, 0 from AllData 
where art in ('A' , 'B') 
union all 
select C.RootLvl, C.Child, AllData.art2, AllData.qty * c.qty, C.lvl + 1 from Tree C 
join AllData 
on C.Child = AllData.art 
) 
select C1.RootLvl as OP, C1.Lvl, C1.Child, C1.Qty from Tree c1 
left join Tree c2 
on c1.child = c2.father and 
    c1.rootLvl = c2.RootLvl 
where C2.RootLvl is null 
order by 1, 2 desc 

SQL Fiddle demo

的A和B表是幾乎相同的。我從他們那裏做了一個簡化它。之後,我們使用遞歸創建樹,最後使用左連接從樹中只獲取樹葉。