the query bellow, unfortunately returns the wrong total of orders. What I want is to know all users whose total orders exceed the sum of their diposit.
SELECT u.id, u.email,u.balance,sum(t.amount - t.fees) as total_disposits ,sum(o.charge) as spent
FROM USERS u
INNER JOIN TRANSACTIONS t ON u.id = t.uid
INNER JOIN ORDERS o ON u.id = o.uid
WHERE total_disposits < spent
GROUP BY u.id;
tables structure :
USERS
-----------------------------------
id | email | balance
-----------------------------------
1 | [email protected] | 15.50
2 | [email protected] | 10.00
3 | [email protected] | 70.00
-----------------------------------
TRANSACTIONS
-----------------------------------
id | user_id | amount | fees
-----------------------------------
1 | 1 | 15.50 | 0.50
2 | 2 | 10.00 | 0.50
3 | 2 | 15.00 | 0.50
4 | 3 | 12.50 | 0.50
5 | 1 | 5.50 | 0.50
-----------------------------------
ORDERS
-----------------------------------
id | user_id | charge
-----------------------------------
1 | 1 | 15.50
2 | 2 | 10.00
3 | 2 | 15.00
4 | 3 | 12.50
5 | 1 | 5.50
-----------------------------------
Thank you
2
Answers
the query inspired from the answer : https://stackoverflow.com/a/71702680/3641989
IMPORTANT : There are no relationships between these tables
You can achieve this multiple ways:
subquery
:CTE
):Result:
Fiddle here.
The reason for this is you cannot use a column alias in your
WHERE
clause, the MySQL Documentation states this:You can also read more about it in the following previous questions:
error
Final Note: your
GROUP BY
was incorrect, it contained theid
column but not theemail
andbalance
column which will throw an aggregation error. To include theemail
andbalance
without adding it to yourGROUP BY
, you can use aJOIN
as I did in my examples above.UPDATE: I’ve added the column
uid
to theJOIN
‘s above. The columnid
was the only provided id column in your sample data. I’ve also updated my Queries, Result, and Fiddle to reflect your Answer above which shows you wanted theSUM
‘s to occur outside of theJOIN
‘s.