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?
Excels SUMIF in SQL In SQL, the picking the rows is separate from the picking of the columns. The the group by and over clauses specify the rows. The column is explicitly used in the <condition> that is put into the case expression. The case expression accepts different values in the when and then branches.
You could create a virtual column that adds up your 96 columns, something like: alter table TABLEA add (MY_TOTAL_COL NUMBER GENERATED ALWAYS AS (col1+col2+col3...) VIRTUAL); Then your query can simply do sum(my_total_col) .
If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.
Example - With Single FieldSELECT SUM(salary) AS "Total Salary" FROM employees WHERE salary > 50000; In this SUM function example, we've aliased the SUM(salary) expression as "Total Salary". As a result, "Total Salary" will display as the field name when the result set is returned.
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
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 |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With