user997112 user997112 - 3 years ago 182
SQL Question

Oracle SQL query to GROUP BY and subtract?

If I have four columns: A, B, C and D in a table how would an Oracle SQL query group by column D, then amongst each grouping select the rows where C = 'c' and for those selected rows, returns the value of B minus A?

Answer Source

SELECT Aggfunction(B - A), D FROM TABLENAME WHERE C='c' GROUP BY D

Replace Aggfunction with aggregate function you want e.g. SUM or AVG. You can only include ungrouped columns from a grouped sql query result set in an aggregate function (which makes sense because you only get one record out per group so have to accumulate the ungrouped columns in some way in order to represent a value per group)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download