Hi I want THE QUERY to sum the number based on the given time interval(I.E. 120 MINUTES)
Type TIME Quantity
----- ---- --------
A 2:00:01 10
A 3:10:20 05
B 4:00:00 01
A 6:10:11 20
HERE IN THE 120 MINUTES I.E. 2 HRS FOR 1ST ROW, WE HAVE 2 A AND 1 B SO SUM IS 15 AND 01. FOR 2ND ROW, IN NEXT TWO HOURS WE HAVE 1 A AND 1 B SO SUM_A IS 05 AND SUM_B IS 01, SHOWN BELOW.
Type TIME Quantity SUM_A SUM_B
----- ---- -------- ------- -----
A 2:00:01 10 15 01
A 3:10:20 05 05 01
B 4:00:00 01 00 01
A 6:10:11 20 20 00
There's a few ways you could do this. Here's two.
Both use analytics to calculate a rolling sum, split by type.
The first does this and pivots the data. The second computes separate functions for A and B:
create table t (
Type varchar2(1),TIME varchar2(10),Quantity int
);
insert into t values ('A','2:00:01',10);
insert into t values ('A','3:10:20',05);
insert into t values ('B','4:00:00',01);
insert into t values ('A','6:10:11',20);
select time, nvl(a_q, 0) sum_a, nvl(b_q, 0) sum_b from (
select type, time,
sum(quantity) over (partition by type order by time) q
from t
order by 2
) pivot (
sum(q) as q for (type) in ('A' as a, 'B' as b)
)
;
TIME SUM_A SUM_B
---------- ---------- ----------
2:00:01 10 0
3:10:20 15 0
4:00:00 0 1
6:10:11 35 0
select type, time, quantity,
nvl(sum(case when type = 'A' then quantity end)
over (partition by type order by time), 0) sum_a,
nvl(sum(case when type = 'B' then quantity end)
over (partition by type order by time), 0) sum_b
from t
order by time;
T TIME QUANTITY SUM_A SUM_B
- ---------- ---------- ---------- ----------
A 2:00:01 10 10 0
A 3:10:20 5 15 0
B 4:00:00 1 0 1
A 6:10:11 20 35 0
I don't understand why sum_b is 1 in your desired output for the first two rows. Surely this should be zero?