Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Take a look at this post <a href="https://stackoverflow.com/questions/860966/calculate-a-running-total-in-sqlserver/13744550">Calculate a Running Total in SQL Server</a></p> <p>If you have SQL Server Denali, you can use new windowed function.<br></p> <p>In SQL Server 2008 R2 I suggest you to use recursive common table expression. Small problem in CTE is that for fast query you have to have identity column without gaps (1, 2, 3,...) and if you don't have such a column you have to create a temporary or variable table with such a column and to move you your data there.</p> <p>CTE approach will be something like this</p> <pre><code>declare @Temp_Numbers (RowNum int, Amount &lt;your type&gt;, EffectiveDate datetime) insert into @Temp_Numbers (RowNum, Amount, EffectiveDate) select row_number() over (order by EffectiveDate), Amount, EffectiveDate from vCI_UNIONALL -- you can also use identity -- declare @Temp_Numbers (RowNum int identity(1, 1), Amount &lt;your type&gt;, EffectiveDate datetime) -- insert into @Temp_Numbers (Amount, EffectiveDate) -- select Amount, EffectiveDate -- from vCI_UNIONALL -- order by EffectiveDate ;with CTE_RunningTotal as ( select T.RowNum, T.EffectiveDate, T.Amount as Total_Amount from @Temp_Numbers as T where T.RowNum = 1 union all select T.RowNum, T.EffectiveDate, T.Amount + C.Total_Amount as Total_Amount from CTE_RunningTotal as C inner join @Temp_Numbers as T on T.RowNum = C.RowNum + 1 ) select C.RowNum, C.EffectiveDate, C.Total_Amount from CTE_RunningTotal as C option (maxrecursion 0) </code></pre> <p>There're may be some questions with duplicates <code>EffectiveDate</code> values, it depends on how you want to work with them - do you want to them to be ordered arbitrarily or do you want them to have equal Amount?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload