2017-05-02 76 views
0

我有表名爲VoucherEntry如何在我的SQL Server標準中使用聚合函數?

這些都是我的記錄,

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列,排序後的記錄將按以上順序顯示

+3

請標記你的DBMS和解釋清楚你的邏輯。 –

+0

你如何訂購你的行? – Lamak

+0

@Lamak by'ID or Date',你可以通過'ID或Date'對錶格進行排序,現在我會更新 –

回答

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 
+0

請稍候讓我檢查 –

+0

@dneoth MR.Genius,我接受你的回答。我不想複製和粘貼。你能給我更多關於你的分區的信息嗎?謝謝 –

+1

@mohamedfaiz:'PARTITION BY'與'GROUP BY'類似,它可以在代金券ID改變的地方重置計算。 – dnoeth

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