How to check if the sum of some records equals the difference between two other records in t-sql?

Posted by Dan Appleyard on Stack Overflow See other posts from Stack Overflow or by Dan Appleyard
Published on 2012-03-23T15:27:51Z Indexed on 2012/03/24 5:29 UTC
Read the original article Hit count: 120

Filed under:
|
|
|

I have a view that contains bank account activity.

ACCOUNT   BALANCE_ROW   AMOUNT   SORT_ORDER
 111           1         0.00        1
 111           0         10.00       2
 111           0         -2.50       3
 111           1         7.50        4
 222           1         100.00      5
 222           0         25.00       6
 222           1         125.00      7
  • ACCOUNT = account number
  • BALANCE_ROW = either starting or ending balance would be 1, otherwise 0
  • AMOUNT = the amount
  • SORT_ORDER = simple order to return the records in the order of start balance, activity, and end balance

I need to figure out a way to see if the sum of the non balance_row rows equal the difference between the ending balance and the starting balance. The result for each account (1 for yes, 0 for no) would be simply added to the resulting result set.

Example: Account 111 had a starting balance of 0.00. There were two account activity records of 10.00 and -2.5. That resulted in the ending balance of 7.50.

I've been playing around with temp tables, but I was not sure if there is a more efficient way of accomplishing this.

Thanks for any input you may have!

© Stack Overflow or respective owner

Related posts about tsql

Related posts about sql-server-2005