Question

I'd like to get the balance from a 'debit' table given an Id.

For instance:

User                      Debit                          

id   |  name              user_from  | user_to   | value  

1    | John               1          |    2      | 13.23          
2    | Marie              1          |    2      | 20          
3    | Peter              2          |    1      | 53
                          1          |    3      | 2.45

I'm John, so I'd like to check my balance to other people.

John's balance = +20.23 (to Marie's) John's balance = -2.45 (to Peter's)

I'm using sqlite 3 for android !

I have created a SQLFIDDLE to see if it helps ! Link: SQLFiddle

Thank you very much for your time and help !

Was it helpful?

Solution

Use correlated subqueries to compute the subtotals for each user:

SELECT id,
       name,
       (SELECT TOTAL(value)
        FROM Debit
        WHERE user_from = User.id
          AND user_to   = 1) -
       (SELECT TOTAL(value)
        FROM Debit
        WHERE user_to   = User.id
          AND user_from = 1) AS amount
FROM User
WHERE amount <> 0;

id          name        amount    
----------  ----------  ----------
2           Marie       19.77     
3           Peter       -2.45     

OTHER TIPS

I'm thinking something like this for the money you owe people (not subtracting money that they owe you): SELECT SUM(value) FROM debit WHERE user_from = (SELECT id FROM User WHERE name=‘John’)

UPDATE: I haven't tested any of this but try this out and just do your subtraction after you have the 2 columns. SELECT SUM(value) AS 'owes' FROM debit WHERE user_from = (SELECT id FROM User WHERE name=‘John’) GROUP BY user_from UNION ALL SELECT SUM(value) AS 'owed' FROM debit WHERE user_to = (SELECT id FROM User WHERE name=‘John’) GROUP BY user_to

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top