5

I have a table named Order with schema as

user_id, state    amount
11       success  100
11       FAILED   10
11       FAILED   10
11       success  17

state can have two values (Success/Failed).

I want to fetch sum(amount) when state = "SUCCESS" - sum(amount) when state = "FAILED" means difference total amount when success - total amount when failed.

I can solve this problem in 2 queries.

A = select id, sum(amount) when state = "SUCCESS"
B = select id, sum(amount) when state = "FAILED"

And solution will be A-B. Is there any way I can achieve this in single sql query?

3 Answers 3

5

use case when

    select user_id,sum(case when state = 'SUCCESS' then amount else 0 end)-sum(case when state = 'FAILED' then amount else 0 end)
from table group by user_id
Sign up to request clarification or add additional context in comments.

Comments

1

Use conditional aggregation:

select id,
       sum(case when state = 'SUCCESS' then amount else - amount end) as total
from t
where state in ('SUCCESS', 'FAILED')
group by id;

I assume that you want this sum per id and not overall in the table.

1 Comment

Missing end for the case expression?
1
select sum(case when state = "SUCCESS" then amount else o end) -
    sum(case when state = "FAILED" then amount else o end)
    from tbl
group by userid

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.