我有两张表,比如
1.GROUP_TABLE
Name Under
--------------
G1 OWNED
G2 G1
G3 G2
G4 G1
G5 G2
G6 G4
G7 G2
STOCK_TABLE
group_name stock
-------------------
G1 10
G2 20
G3 30
G4 10
G5 10
G6 10
G7 20
在grouptable中,有一些组属于另一组。 如果我需要G1的库存那么它将重新运行110(与G1相关的所有组的总和)。 如下:(G1) - >(G2,G4) - >(G5,G6,G7)。 与G2 -80相同,因为(G2) - >(G3,G5,G7) 对于G3,G4,G5,G6,G7等等。
我需要像
这样的结果TillGroup Stock
-------- --------
G1 110
G2 80
G3 30
G4 20
G5 10
G6 10
G7 20
请建议我任何sql查询女巫将提供相同的结果 提前谢谢。
答案 0 :(得分:3)
您对此使用递归查询:
with tree as
(
select name as master_name, name as descendant_name, under from group_table
union all
select
parent.name as master_name,
child.descendant_name as descendant_name,
parent.under
from group_table parent
join tree child on child.under = parent.name
)
select tree.master_name, sum(stock_table.stock)
from tree
join stock_table on stock_table.group_name = tree.descendant_name
group by tree.master_name
order by tree.master_name;
请参阅SQL小提琴http://www.sqlfiddle.com/#!3/4e557/26。
答案 1 :(得分:1)
编辑:仔细阅读问题之后,我的答案将无效,因为它不会穿越儿童的孩子。
select G.NAME, SUM(G1S.STOCK) + GS.STOCK
from GROUP_TABLE G -- consider this the parent
JOIN STOCK_TABLE GS ON GS.GROUP_NAME = G.NAME -- Get its stock number
JOIN GROUP_TABLE G1 ON G1.UNDER = G.NAME -- self-join to get all its children
JOIN STOCK_TABLE G1S ON G1S.GROUP_NAME = G1.NAME -- get the stock number for each of its children
GROUP BY G.NAME, GS.STOCK
抱歉,我没有编译它来检查语法。可能存在一些小的语法错误。