Hello everyone i am trying to make a query with two LEFT JOINs and something is not working, i would love some help.
Let me introduce you the tables i'm working on:
Code:
USERS
----------+-----------+
| user_id | user_name |
----------+-----------+
| 1 | Jhon |
| 2 | Paul |
| 3 | George |
| 4 | Ringo |
----------+-----------+
PAYMENT_TRANSACTIONS
--------------+------------+
| trx_user_id | trx_amount |
--------------+------------+
| 1 | 100.00 |
| 1 | -87.00 |
| 3 | 55.30 |
| 3 | 10.00 |
--------------+------------+
ORDERS
----------------+--------------+
| order_user_id | order_amount |
----------------+--------------+
| 3 | 4.00 |
| 3 | 10.00 |
| 1 | 15.00 |
----------------+--------------+
I want to get a table with all the user names in a column, the sum of deposits and sum of withdrawals for each user in other two colums, and the sum of orders for each user in a fourth column. (widthdrawals are negative trx_amount and deposits are positive trx_amount)
Following the example above the result would look something like:
Code:
------------+----------+--------------+--------+
| user_name | Deposits | widthdrawals | orders |
------------+----------+--------------+--------*
| Jhon | 100.00 | -87.00 | 15.55 |
| Paul | 00.00 | 00.00 | 00.00 |
| George | 65.30 | 00.00 | 25.00 |
| Ringo | 00.00 | 00.00 | 00.00 |
------------+----------+--------------+--------+
I wrote a query that is working fine but doesn't include the sum of orders for each user:
Code:
SELECT
u.user_name,
SUM(CASE WHEN t.trx_amount>0 THEN t.trx_amount ELSE 0 END) AS deposits,
SUM(CASE WHEN t.trx_amount<0 THEN t.trx_amount ELSE 0 END) AS withdrawals
FROM
users AS u
LEFT JOIN payment_transactions AS t ON t.trx_user_id=u.user_id
GROUP BY
u.user_id
When i try to include a second left join the sums are messed and all numbers lose any meaning:
Code:
SELECT
u.user_name,
SUM(CASE WHEN t.trx_amount>0 THEN t.trx_amount ELSE 0 END) AS deposits,
SUM(CASE WHEN t.trx_amount<0 THEN t.trx_amount ELSE 0 END) AS withdrawals
SUM(o.order_amount)
FROM
users AS u
LEFT JOIN payment_transactions AS t ON t.trx_user_id=u.user_id
LEFT JOIN orders AS o ON o.order_user_id=u.user_id
GROUP BY
u.user_id
As i said before, the first query is doing well but i have problems including the sum of orders for each user.
Any help would be really appreciated!
Thanks in advance