1

I have table with following structure:

TestTable (ID INT, LoanID INT, Amount INT)

ID  LoanID  Amount
1   1        20
2   1        30
3   1        15
4   2        40
5   2        20
6   3        50

I want to calculate LoanAmounts with this scenario

ID  LoanID  Amount  Sum
1   1       20      20
2   1       30      50
3   1       15      65
4   2       40      40
5   2       20      60
6   3       50      50

What is the best way to get this Sum collumn (Of course without cursor :))

tungula
  • 578
  • 1
  • 6
  • 12

6 Answers6

3

You can use a correlated sub-query to get the running-totals:

SELECT t.ID, t.LoanID, t.Amount,
       [Sum] = (SELECT SUM(AMOUNT)
                FROM TestTable t2
                WHERE t.LoanID=t2.LoanID
                AND t2.ID <= t.ID)
FROM TestTable t

Demo

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

Unfortunately SQL Server 2008 doesn't have a clean function to do a cumulative sum, so you need to add up all of the "previous" rows with the same LoadID:

SELECT
  ID,
  LoanID,  
  Amount,
  (SELECT SUM(Amount) FROM TestTable t2 WHERE t2.LoanID = t.LoanID AND t2.ID <= t.ID) Sum
FROM TestTable t
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0
select ID, LoanID, Amount, 
       (select sum(Amount)
        from TestTable A
        where  A.LoanID = B.LoanID and
               A.ID <= B.ID
       ) as Sum
from TestTable B;
Spider
  • 367
  • 3
  • 15
0

By using windowing function:

select *, sum(amount) over (partition by loanid order by id) as "sum" from testtable;

SQL server 2012: http://sqlfiddle.com/#!6/dc108/8

SQL server 2008: http://sqlfiddle.com/#!3/dc108/10

It works on SQL server 2012, but not on sql server 2008 using sqlfiddle.

Mladen Uzelac
  • 1,173
  • 1
  • 10
  • 14
0

Try this

  SELECT b.id,a.LoanID,b.Amount,
           Sum(a.Amount) AS [Sum]
    FROM   #temp_table a
    JOIN   #temp_table b ON a.id <= b.id
                  AND a.LoanID = b.LoanID
    GROUP  BY b.id,a.LoanID,b.Amount
PP006
  • 681
  • 7
  • 17
-3
SELECT SUM(column_name) FROM table_name;
Klyse
  • 59
  • 2
  • 11