Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
jigsh
Starting Member
6 Posts |
Posted - 2008-09-15 : 13:57:36
|
| I have following data:Date Id Amount2/1/2008 1 -30002/1/2008 1 -30002/1/2008 1 30002/1/2008 1 30003/1/2008 2 -35003/1/2008 2 -30003/1/2008 2 35003/1/2008 2 5003/1/2008 2 30004/1/2008 3 -38004/1/2008 3 -30004/1/2008 ? -5004/1/2008 3 5004/1/2008 3 33004/1/2008 3 3000I would like to have Stored Procedure or View which returns the data with new colum called Balanace so the results set look like this.Date Id Amount Balance2/1/2008 1 -3000 30002/1/2008 1 -3000 60002/1/2008 1 3000 30002/1/2008 1 3000 03/1/2008 2 -3500 35003/1/2008 2 -3000 65003/1/2008 2 3500 30003/1/2008 2 500 25003/1/2008 2 3000 -5004/1/2008 3 -3800 33004/1/2008 3 -3000 63004/1/2008 ? -500 68004/1/2008 3 500 63004/1/2008 3 3300 30004/1/2008 3 3000 0Does any have idea to accomplish this? Can I write viewThanksJigsh |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-09-15 : 14:06:31
|
| [code];With CTE(Seq,Date, Id, Amount) AS(SELECT ROW_NUMBER() OVER(PARTITION BY Date,Id ORDER BY Date), Date, Id, AmountFROM YourTable)SELECT c1.date,c1.Id,c1.Amount,COALESCE(c2.PrevBal,0)-c1.Amount AS BalanceFROM CTE c1OUTER APPLY (SELECT TOP 1 Balance AS PrevBal FROM CTE WHERE Date=c1.Date AND Id=c1.Id AND Seq<c1.Seq ORDER BY Seq DESC)c2[/code] |
 |
|
|
jigsh
Starting Member
6 Posts |
Posted - 2008-09-15 : 14:34:25
|
| Hi Visakh16...thanks for your quick response but I am getting following error:Invalid column name 'Balance'. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-09-15 : 15:09:11
|
| [code];With CTE(Seq,Date, Id, Amount) AS(SELECT ROW_NUMBER() OVER(ORDER BY Date,Id), Date, Id, AmountFROM YourTable)SELECT c1.date,c1.Id,c1.Amount,ABS(COALESCE(c2.PrevAmt,0)+c1.Amount) AS BalanceFROM CTE c1OUTER APPLY (SELECT SUM(Amount) AS PrevAmt FROM CTE WHERE Seq<c1.Seq)c2[/code] |
 |
|
|
|
|
|
|
|