2

I have a table shipments:

--------------------------
id | event    | quantity |
--------------------------
1  | received | 20       |
2  | sent     | 30       | 
3  | received | 45       |

I want a query that will sum all the received quantities, and subtract that value from the sent quantities. The query should return a result of 35.

SELECT SUM(quantity)
FROM shipments
WHERE event = 'received';

This query returns 65. How can I get it to also subtract the sent quantity (and get a result of 35)?

1 Answer 1

6

Use a CASE expression that puts a sign depending on event.

SELECT sum(CASE event
             WHEN 'received' THEN
               quantity
             WHEN 'sent' THEN
               -quantity
             ELSE
               0
           END)
       FROM shipments;
Sign up to request clarification or add additional context in comments.

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.