我在做一些递归过程时遇到问题。 这是我制作的剧本,效果很好(除了我将要解释的总和):
;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
,但我无法正确执行
答案 0 :(得分:3)
使用group by
SELECT firstcolname, secondcolname, sum(thircolname) GROUP BY firstcolname, secondcolname
答案 1 :(得分:0)
最后一个查询应该是:
select MOTHER, CHILD, sum(quantity) quantity
from result
where mother not in (select child from bilangammestest )
group by MOTHER, CHILD