user1464251
user1464251

Reputation: 333

SQL issue aggregating values based on time

I need a running total of value 1 and value 2.

I have a table that looks like this:

Time | Plus Value | Minus Value 2 | 
0         30           10             
10        20           15
15        10           20
...

I would like to be able to get the following table

Time | Plus Value | Minus Value 2 | Total
0         30           10             20           
10        20           15             25
15        10           20             15
...

I would like to be able to select something like this

select time, plus_value, minus_value(sum(plus_value) - sum(minus_value)) as total
from table
where time <= time

How can I do this? I am forced to group by time which then does not give me the desired result.

Upvotes: 0

Views: 82

Answers (2)

blearn
blearn

Reputation: 1208

I don't understand your where clause: where time <= time?

Anyways, I believe that your query could be implemented like:

select time, plus_value, minus_value, (plus_value - minus_value) as total
from table;

Upvotes: 0

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

select time,
       plus_value,
       minus_value,
       sum(plus_value - minus_value) over(order by time rows unbounded preceding) as total
from table

Upvotes: 4

Related Questions