层次结构SQL Server连接两个不同的表

时间:2016-05-12 00:42:20

标签: sql sql-server hierarchy

我在进行层次结构查询时遇到问题。

我在MS SQL DB中有以下内容:

表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加入数量,也不知道如何为第一个表上的所有项运行此查询。

有人可以帮我吗?

非常感谢!

1 个答案:

答案 0 :(得分: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表几乎相同。我从他们那里做了一个简化它。之后我们使用递归来创建树,最后我使用左连接只从树中获取叶子。