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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Financial Balance

Author  Topic 

FernandoLorival
Starting Member

19 Posts

Posted - 2013-09-27 : 12:48:10
Hi all,
I have a financial table that holds financial transaction, one of the fields is Balance. When a transaction is posted that field is populated with an amount, when the client pays that amount or a fraction of the amount, another transaction is created (row) that will deduct from the initial balance. This happens until the balance is 0.
Now, I need a report that shows only my open balances, basically the last transaction posted against the client.

Here's my code example:

DECLARE @TEMP1 TABLE (ClientNo INT, TransactionID INT, TransAmount INT, Balance INT);

INSERT @TEMP1
VALUES (1, 1, 123, 123),
(1, 2, -123, 0),
(2, 1, 500, 500),
(3, 1, 45000, 45000),
(4, 1, 45, 45),
(5, 1, -234, -234),
(5, 2, 123, -111),
(6, 1, 234234, 234234)


In this case I would like to get the information for Client 2,3,4,5 and 6.
NOTE: For client 5 I only want to show the last line, open balance -111.


Thank you all for your time.


James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-09-27 : 12:55:29
[code]SELECT * FROM
(
SELECT *,
ROW_NUMBER() OVER(PARTITION BY clientNo ORDER BY TRansactionId DESC) AS RN
FROM
@Temp1
)s WHERE Balance <> 0 AND RN = 1[/code]
Go to Top of Page

FernandoLorival
Starting Member

19 Posts

Posted - 2013-09-27 : 13:01:14
Thank you James,
That works!
:)
Go to Top of Page
   

- Advertisement -