On a single column : Algebraic operation on Aggregate functions

时间:2016-04-21 22:18:18

标签: sql oracle11g

Is it possible on the same SQL Select Query (no function/procedure nor PL/SQL) to compute an algebraic operation on two aggregate functions ?

|  id ||  A  |
|-----||-----|
|  1  || 10  |
|  2  || 20  |
|  3  || 30  |
|  4  || 40  |


SELECT (SELECT SUM(A) FROM Table Where 'id is even') - (SELECT SUM(A) FROM Table Where 'id is odd')
FROM TABLE
WHERE 'condition'

Any idea ?

ps : My databse is Oracle 11g

1 个答案:

答案 0 :(得分:4)

You can do it as this:

select sum(case when mod(id,2)=0 then A else 0 end) -
       sum(case when mod(id,2)=0 then 0 else a end)
  from test
 where yourCondition

The SQLFiddle is a MySql sample, since the Oracle also have mod function it should work as is.

See it working here: http://sqlfiddle.com/#!9/1ba756/2