我有两个表,例如
1.GROUP_TABLE
Name Under
--------------
G1 OWNED
G2 G1
G3 G2
G4 G1
G5 G2
G6 G4
G7 G2
库存表
group_name stock ------------------- G1 10 G2 20 G3 30 G4 10 G5 10 G6 10 G7 20
在组表中,有一些组属于另一个组。 如果我需要 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查询都会为我提供相同的结果 提前致谢。
最佳答案
您可以为此使用递归查询:
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 fiddle http://www.sqlfiddle.com/#!3/4e557/26 .
关于Sql 查询查找相关行中列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27293462/