如何在我的SQL Server标准中使用聚合函数?

时间:2017-05-02 19:41:37

标签: sql sql-server stored-procedures aggregate-functions

我有一个名为VoucherEntry

的表格

这些是我的记录,

ID    VoucherOnlineID    TransactionNumber    Store    Amount  
-------------------------------------------------------------
120    137                26                   1001     100
126    137                22                   2000     -56
128    137                30                   3000     -20
133    137                11                   2000     -5

现在我要添加2列持有量和余额。如果VoucherEntry.Amount = 100那么进位列应为0,否则它应显示如下

期待输出

ID    VoucherOnlineID    TransactionNumber    Store    Carry    Amount   Balance
---------------------------------------------------------------------------------
120    137                26                   1001     0        100      100
126    137                22                   2000     100      -56      44
128    137                30                   3000     44       -20      24
133    137                11                   2000     24       -5       19

更新

  

我们可以按记录排序ID列或Date列,排序后的记录将按上述顺序显示

2 个答案:

答案 0 :(得分:2)

您需要两种累积和的变体:

SELECT 
   VoucherOnlineID
  ,TransactionNumber
  ,Store
  ,Coalesce(Sum(Amount) -- Cumulative Sum of previous rows
            Over (PARTITION BY VoucherOnlineID 
                  ORDER BY DATE -- or whatever determines correct order
                  ROWS BETWEEN Unbounded Preceding AND 1 Preceding), 0) AS Carry
  ,Amount
  ,Sum(Amount) -- Cumulative Sum including current row
   Over (PARTITION BY VoucherOnlineID 
         ORDER BY DATE -- or whatever determines correct order
         ROWS Unbounded Preceding) AS Balance
FROM VoucherEntry

答案 1 :(得分:0)

sql Server 2008及以下

declare @t table(ID int,VoucherOnlineID int,TransactionNumber int,Store int,Amount int)  
insert into  @t  VALUES
(120,137,26,1001,100)
,(126,137,22,2000,-56)
,(128,137,30,3000,-20)
,(133,137,11,2000,-5 )

select *
,isnull((Select sum(Amount) from @t t1 
where t1.VoucherOnlineID=t.VoucherOnlineID 
and t1.id<t.id  ) ,0)Carry    
,isnull((Select sum(Amount) from @t t1 
where t1.VoucherOnlineID=t.VoucherOnlineID 
and t1.id<=t.id  ) ,0)Balance
from  @t t