递归运行余额(获得现金奖励)

时间:2018-11-03 14:25:45

标签: tsql sql-server-2012 window-functions

我正在尝试实施以下业务场景-

我将批量获取用户的兑换数据。我需要维护这些赎回的分类帐,以抵销同一用户的各种收入。这是示例数据。

DECLARE @TransData AS TABLE(TransDataID int IDENTITY(1,1), PropertyID int, TransactionAmount decimal(18,2))

INSERT INTO @TransData (PropertyID, TransactionAmount)
SELECT 1,10
UNION
SELECT 1,20
UNION
SELECT 1,30
UNION
SELECT 1,40
UNION
SELECT 1,50
UNION
SELECT 1,60
UNION
SELECT 1,70

DECLARE @AdjustmentData as TABLE ( DailyBalanceID bigint, AvailableBalance decimal(18,8), [PropertyID] bigint )
INSERT INTO @AdjustmentData
VALUES
( 1000092, 80.00000000, 1 ), 
( 1000093, 101.00000000, 1 ), 
( 1000094, 100.00000000, 1 ), 
( 1003708, 111.00000000, 1 ), 
( 1022176, 10.00000000, 1 );

示例

TransData 
ID  TransactionAmount
1  10
2  20
3  30
4  40
5  50
6  60
7  70

AdjustmentData 
DailyBalanceID  AvailableBalance
1000092  80
1000093  101
1000094  100
1003708  111
1022176  10

AdjustmentData  TransData  
ID  TransactionAmount  DailyBalanceID  AvailableBalance  AdjustmentData.TransactionAmount  Calculation
1000092  80  1  10 
1000092  70  2  20  AdjustmentData.AvailableBalance (80) -= TransData.TransactionAmount (10)
1000092  50  3  30  AdjustmentData.AvailableBalance (70) -= TransData.TransactionAmount (20)
1000092  20  4  40  AdjustmentData.AvailableBalance (50) -= TransData.TransactionAmount (30)
1000092  -20   
1000093  101  5  50 
1000093  41  6  60  AdjustmentData.AvailableBalance (101) -= (TransData.TransactionAmount (50)+LastRowNegativeBalance(-20))
1000093  -19   
1000094  100  7  70  AdjustmentData.AvailableBalance (100) -= (TransData.TransactionAmount (70)+LastRowNegativeBalance(-19))
1000094  11   
  

Blockquote

以下图像中的预期输出 enter image description here

0 个答案:

没有答案