0

I have a table with an operation and an amount columns. The opearation is an ENUM with two values: "in", "out". amount is just an INT.

I would like to sum the amounts "in" and subtract the sum of the amounts "out" in a single query.

I can extract a single value at a time:

SELECT SUM(amount) as total_in
FROM movements
WHERE operation like "in"

but I have no idea how to do both in one query...

2
  • Can you share sample input data and expected output? Commented Aug 21, 2022 at 10:47
  • You can look into GROUP BY and aggregate functions. Commented Aug 21, 2022 at 10:53

2 Answers 2

1

Hello Please test this: (CTE-Common Table Expressions):

WITH cte1 AS (SELECT SUM(amount) AS total_in FROM movements WHERE operation = "in")
,cte2 AS (SELECT SUM(amount) AS total_out FROM movements WHERE operation = "out")
SELECT *, (total_in - total_out) as difference FROM cte1 JOIN cte2;

If we test it with some fake data:

FD

Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know about CTE, interesting. As far as your query, is almost identical to mine. Thanks for taking the time!
Hi @IDK, Yes! Not a big difference. For me, CTE's are very important topic to learn in sql, together with window functions; because It gives you amazing flexibility to solve challenging problems. You can learn more about CTE's here: dev.mysql.com/doc/refman/8.0/en/with.html
0

I've found a solution, here it is:

with deposits as (
     select sum(amount) as total_deposits
     from movements
     where operation like "deposit"),
    withdrawals as (
         select sum(amount) as total_withdrawals
         from movements
        where operation like "withdrawal")
select (withdrawals.total_withdrawals - deposits.total_deposits ) as net_profit
from deposits cross join withdrawals;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.