13

I have the data in the follow way:

ITEM  LOCATION  UNIT RETAIL  QUANTITY 
100     KS         10          -10
200     KS         20           30

I want the sum of positive quantities (quantity > 0) and sum of negative quantities (quantity < 0).

How do I get those column sum based on condition?

2 Answers 2

27

You can use SUM(CASE ... ):

SELECT item, location,
   SUM(CASE WHEN quantity > 0 THEN quantity ELSE 0 END) AS positive_sum,
   SUM(CASE WHEN quantity < 0 THEN quantity ELSE 0 END) AS negative_sum
FROM your_table
GROUP BY item, location;

LiveDemo

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

Comments

4

You can use GREATEST and LEAST in conjunction with the SUM function:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE table_name ( ITEM, LOCATION, QUANTITY ) AS
          SELECT 100, 'KS', -10 FROM DUAL
UNION ALL SELECT 100, 'KS', -10 FROM DUAL
UNION ALL SELECT 100, 'KS', -20 FROM DUAL
UNION ALL SELECT 100, 'KS',  10 FROM DUAL
UNION ALL SELECT 100, 'KS',   5 FROM DUAL
UNION ALL SELECT 200, 'KS',  10 FROM DUAL
UNION ALL SELECT 200, 'KS',  20 FROM DUAL
UNION ALL SELECT 200, 'KS',   5 FROM DUAL

Query 1:

SELECT item,
       location,
       SUM( GREATEST( quantity, 0 ) ) AS positive_quantities,
       SUM( LEAST( quantity, 0 ) )    AS negative_quantities
FROM   table_name
GROUP BY item, location

Results:

| ITEM | LOCATION | POSITIVE_QUANTITIES | NEGATIVE_QUANTITIES |
|------|----------|---------------------|---------------------|
|  100 |       KS |                  15 |                 -40 |
|  200 |       KS |                  35 |                   0 |

2 Comments

I like the idea of hiding CASE with GREATEST/LEAST :) Could you compare execution plans with my solution?
@lad2025 Unsurprisingly - they both have identical plans. If you wish to profile them you can see if they have different performance (but I doubt it as they do exactly the same thing). Ultimately it comes down to which is more readable/maintainable/easier to type/etc...

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.