I have a table [Transaction] which is designed to store values of transactions of players who play backgammon with money. The house can give credit (buy in the game and pay later) or debit (pay cash in hand). There are four types of transactions (Debit, Credit) and ('Credit Settlement' - customer pays back some or all of what he owes, and 'Debit Settlement' - payment by the house if the house owes money to the player). What I'm trying to do is to find the balance. I have tried a lot of sql statements but I'm always missing something and the balance is not correct.
A simple scenario is: Customer walks in, buys in for 300 in credit. He cashes out 100, so he owes 200 to the house. He comes the next day, buys in for 100 credit (so now he owes 300) and ends up cashing out 1000. The house pays him 500 but owes him 200 more. The house pays 200 to the customer so this is stored as 'Debit Settlement'.
Here is what I have so far but the results are not always correct:
SELECT SUM(Cashout) - ((SELECT COALESCE (SUM(Paid), 0) AS Expr1
FROM [Transaction]
WHERE (Type = 'Credit Settlement')) + SUM(Buyin) +
(SELECT COALESCE (SUM(Paid), 0) AS Expr1
FROM [Transaction] AS Transaction_3
WHERE (Type = 'Debit Settlement') AND (Paid IS NOT NULL))) AS OutstandingDebit
FROM [Transaction] AS Transaction_1
WHERE (Type <> 'Debit Settlement') AND (Cashout >= 0) AND (CustomerID = 132)
CustomerID
fit in and, more importantly, why isn't it referenced in the two subqueries? – Tim Rogers