I'm currently stuck on how to create a statement that shows daily overdraft statements for a particular council.
I have the following, councils, users, markets, market_transactions, user_deposits.
market_transaction run daily reducing user's account balance. When the account_balance is 0 the users go into overdraft (negative). When users make a deposit their account balance increases.
I Have put the following tables to show how transactions and deposits are stored. if I reverse today's transactions I'm able to get what account balance a user had yesterday but to formulate a query to get the daily OD amount is where the problem is.
USERS
user_id | name | account_bal |
---|---|---|
1 | Wells | -5 |
2 | James | 100 |
3 | Joy | 10 |
4 | Mumbi | -300 |
DEPOSITS
id | user_id | amount | date |
---|---|---|---|
1 | 1 | 5 | 2021-04-26 |
2 | 3 | 10 | 2021-04-26 |
3 | 3 | 5 | 2021-04-25 |
4 | 4 | 5 | 2021-04-25 |
TRANSACTIONS
id | user_id | amount_tendered | date |
---|---|---|---|
1 | 1 | 5 | 2021-04-27 |
2 | 2 | 10 | 2021-04-26 |
3 | 3 | 15 | 2021-04-26 |
4 | 4 | 50 | 2021-04-25 |
The Relationships are as follows,
COUNCILS
council_id | name |
---|---|
1 | a |
2 | b |
3 | c |
MARKETS
market_id | name | council_id |
---|---|---|
1 | x | 3 |
2 | y | 1 |
3 | z | 2 |
MARTKET_USER_LINK
id | market_id | user_id |
---|---|---|
1 | 1 | 3 |
2 | 2 | 2 |
3 | 3 | 1 |
I'm running this SQL query to get the total amount users have spent and subtracting with the current user account balance. Don't know If I can use this to figure out the account_balance for each day.
SELECT u.user_id, total_spent, total_deposits,m.council_id
FROM users u
JOIN market_user_link ul ON ul.user_id= u.user_id
LEFT JOIN markets m ON ul.market_id =m.market_id
LEFT JOIN councils c ON m.council_id =c.council_id
LEFT JOIN (
SELECT user_id, SUM(amount_tendered) AS total_spent
FROM transactions
WHERE DATE(date) BETWEEN DATE('2021-02-01') AND DATE(NOW())
GROUP BY user_id
) t ON t.user_id= u.user_id
ORDER BY user_id, total_spent ASC
// looks like this when run
| user_id | total_spent | council_id |
|-------------|----------------|------------|
| 1 | 50.00 | 1 |
| 2 | 2.00 | 3 |
I was hoping to reverse transactions and deposits done to get the account balance for a day then get the sum of users with an account balance < 0... But this has just failed to work.
The goal is to produce a query that shows daily overdraft (Only SUM the total account balance of users with account balance below 0 ) for a particular council.
Expected Result
date | council_id | o_d_amount |
---|---|---|
2021-04-24 | 1 | -300.00 |
2021-04-24 | 2 | -60.00 |
2021-04-24 | 3 | -900.00 |
2021-04-25 | 1 | -600.00 |
2021-04-25 | 2 | -100.00 |
2021-04-25 | 3 | -1200.00 |