Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate difference in Oracle table from sum

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading