1

WALLET TABLE

ID IS_SPEND HOWMUCH

  1. true. 500
  2. false. 1000
  3. true. 5

I want to calculate how much money I have after several transactions.

spend as spend money and not spend as earn money

I tried

select is_spend, sum(howmuch) from table group by is_spend

But it cannot reach my goal.

I don't know how can I get the result I want,

just output 495 is perfect.

3 Answers 3

2

You seem to want aggregation:

select sum(case when is_spend then -howmuch else howmuch end)
from table 
Sign up to request clarification or add additional context in comments.

Comments

1

Could subtract two conditional sums:

SELECT COALESCE (sum(howmuch) FILTER (WHERE NOT IS_SPEND), 0)
     - COALESCE (sum(howmuch) FILTER (WHERE IS_SPEND), 0)  AS total
FROM   tbl;

But you'll need to add COALESCE if you cannot be certain that both types exist.

Comments

1

try this:


SELECT (SELECT SUM(HOWMUCH) FROM TABLE WHERE IS_SPEND = '0') - (SELECT SUM(HOWMUCH) FROM TABLE WHERE IS_SPEND = '1') AS GOAL;

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.