如何使此查询递归 Sql 服务器?

How can I make this query recursive Sql Server?

我有这个 table 余额结构 table:

这是视图:

我也有这样的金额结构 table:

这是金额的查看模式 table:

首先,我需要获取特定日期的金额值 Table:

通过此查询,我在日期 07/07/2016 获得了金额 300。 达到这个数字后,我需要使用 Balances table 进行递归查询。 最终结果应该是这样的:

    Name   abstractAmount   addAmount  Balance
   -----   --------------   ---------  -------
   Josep                      100        400       
   Maria       50                        350
   George                     60         410
   Julianne    25                        385

这是什么?这个结果是从金额 table 中取 300 得到的,对于余额 table 中的每一行,我看到: 如果第一行中的 abstracAmount 不为空,我进行此数学计算:balance = (300 - abstractAmount),如果为空且 addAmount 列有值,我进行此数学计算 balance = (300 + addAmount) 在其余的行中,我做同样的事情,但计算不是在 300 上,而是在最后一行余额上: 例如: 在第一行中,余额是 400,因为 addamount 有值,所以我做这个计算:300 + 100 = 400 在第二行中,余额为 350,因为 abstractAmount 不为空,所以我取最后一行的余额值并进行计算:400 - 50 = 350。 其余行也是如此,只有第一行采用金额 table.

的余额值

Notes:
1. Always the column abstractAmount subtracts values, and the addAmount column sum values.

  1. Always one of this columns (abstractAmount | addAmount) will be empty .

  2. Only the first row takes the value to make the mathematical calculation for the Amounts table, the rest of rows takes the value for the row before.

我怎样才能得到这个最终结果? :

       Name     abstractAmount  addAmount   Balance
       -----   --------------   ---------  -------
       Josep                      100        400       
       Maria       50                        350
       George                     60         410
       Julianne    25                        385

我接受建议,谢谢。

您可以使用 window 函数代替递归。更具体地说,对 rows unbounded preceding 求和得到 运行 总数(+ 开始余额):

select *,300 +  sum(isnull(addAmount,0) - ISNULL(abstractAmount,0))  over (order by id rows unbounded preceding) Balance 
from Balances

isnull(addAmount,0) - ISNULL(abstractAmount,0) 只是每一行的突变。 over (order by id rows unbounded preceding) 根据 id 将总和范围限定为当前行和所有前面的行。

要从金额 table 中获取基数,您只需将 (select ...where date..) 作为值而不是“300”或更多漂亮:交叉连接到金额 table:

select b.*, a.dateInsertion,a.amount, a.amount +  sum(isnull(addAmount,0) - ISNULL(abstractAmount,0))  over (order by b.id rows unbounded preceding) Balance 
from Balances b
cross join Amounts a
where a.dateInsertion = '20160707'

使用没有 where 的交叉连接,您将获得所有可能的余额