L
L
Light7772016-03-10 18:31:10
Oracle
Light777, 2016-03-10 18:31:10

How to calculate the sum and difference of row values ​​in Oracle?

Hello everyone, there is a table with two columns
id cost
1 500
2 100
3 300
How can I add the first two rows and subtract the third?
so that it is 500 + 100-300 = 300
so that one cell comes out with an answer of 300

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2016-03-11
@a1go1ov

with data as (
select 1 as id, 500 as cost from dual union all
select 2 as id, 100 as cost from dual union all
select 3 as id, 300 as cost from dual union all
select 4 as id, 200 as cost from dual union all
select 5 as id, 100 as cost from dual union all
select 6 as id, -800 as cost from dual
)

select batch, sum(cost) as total
form (
    select ceil(rownum/3) batch,
            ( case when rownum < max(rownum) over (partition by ceil(rownum/3)) then cost else -cost end ) as cost
    from data
    order by id
)
group by batch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question