我在执行一些递归过程时遇到问题。
这是我制作的脚本,效果很好(除了我稍后要解释的总和):

;WITH RESULT (MOTHER, CHILD, QUANTITY) as
(
    select Mother, Child, CONVERT(Numeric(10,0), Quantity) as Quantity
    from bilangammestest

    union all

    select M.mother, R.Child, CONVERT(Numeric(10,0), M.quantity * R.Quantity) as Quantity
    from Result R
    INNER JOIN bilangammestest M ON M.Child = R.Mother
)

select * from result
where mother not in (select child from bilangammestest)

这是我的表 Bilangammestest 上的数据:
Z A 1
Z Y 1
A B 2
Y B 2
B C 3

这是我得到的结果:
Z A 1
Z Y 1
Z C 6
Z C 6
Z B 2
Z B 2

这是我想要的最终结果:
Z A 1
Z Y 1
Z C 12
Z B 4

我试图做一个 sum 但我不能正确地做

最佳答案

最后一个查询应该是:

select MOTHER, CHILD, sum(quantity) quantity
from result
where mother not in (select child from bilangammestest )
group by MOTHER, CHILD

关于sql-server - 递归过程中的 SUM,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29895608/

10-12 12:48
查看更多