sql-server - 递归过程中的 SUM

标签 sql-server recursive-query

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

;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

我尝试进行求和,但无法正确完成

最佳答案

使用分组依据

SELECT firstcolname, secondcolname, sum(thircolname) GROUP BY firstcolname, secondcolname

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

相关文章:

sql-server - 使用 PostgreSQL 外部数据包装器从 SQL Server 查询数据时的数据量问题

sql - 在大型数据库中为简单查询建立索引

sql-server - SQL Server 2008 根据 1 个唯一列查找行并在第二列中查找重复项

c# - 在 C# 中更改 SQL Server 存储过程

.net - 在 SQL Server 2008 的 'From' 子句中使用表名变量

postgresql - 如何确定流网络有向图上的 Strahler 数

mysql - 如何获得任意连续范围内的最大值

python - 使用 Python 和 PostgreSQL 管理多个类别树

sql - DB2中的递归查询以获取链中的所有项目

mysql - 如何创建MySQL分层递归查询