Home > Software engineering >  Calculate difference in Oracle table from sum
Calculate difference in Oracle table from sum

Time:04-26

I have a table which looks as followed:

ID | Value
A  | 2
A  | 5
A  | 6 
B  | 1
B  | 7
B  | -3

I am currently using a statement as followed

select ID, sum(VALUE) 
where ...
group by ID.

Now I need the difference from A and B.

Could anyone send me on the right path? I am working with Oracle.

CodePudding user response:

Use conditional aggregation:

SELECT SUM(CASE WHEN id = 'A' THEN "Value" ELSE 0 END) -
       SUM(CASE WHEN id = 'B' THEN "Value" ELSE 0 END) "Difference"
FROM tablename;

See the demo.

  • Related