Hi,
I wish Oracle allowed analytics to use self reference so I wouldn't need to learn the model clause (intimidating).
My reference to manual aggregates comes from this :
http://www.oracle-developer.net/display.php?id=215 Apparently some versions can be solved with CONNECT BY (like factorials) because you only need the level.
I used to think recursive WITH was just a replacement for CONNECT BY but this shows it is truly self referencing and can do things CONNECT BY can't (I think) :
drop table test;
create table test (stock_date DATE, stock_in NUMBER(5), stock_out NUMBER(5), stock_val NUMBER(5));
--create table test (stock_date DATE, stock NUMBER(5), stock_in NUMBER(5), stock_out NUMBER(5), stock_val NUMBER(5));
INSERT INTO test VALUES (TO_DATE('010118', 'MMDDRR'),100,0,null);
INSERT INTO test VALUES (TO_DATE('020118', 'MMDDRR'),10,20,null);
INSERT INTO test VALUES (TO_DATE('030118', 'MMDDRR'),5,5,null);
INSERT INTO test VALUES (TO_DATE('040118', 'MMDDRR'),0,90,null);
INSERT INTO test VALUES (TO_DATE('050118', 'MMDDRR'),2,5,null);
INSERT INTO test VALUES (TO_DATE('060118', 'MMDDRR'),20,5,null);
INSERT INTO test VALUES (TO_DATE('070118', 'MMDDRR'),10,30,null);
COMMIT;
WITH
NumberedRows AS (
SELECT ROW_NUMBER() OVER(ORDER BY stock_date) Pos, stock_date, t.ROWID Row_ID, stock_in - stock_out change
FROM test t),
SumFloor(Pos, stock_date, Row_ID, change, total) AS (
SELECT Pos, stock_date, Row_ID, 0 change, change total
FROM NumberedRows r
WHERE Pos = 1
UNION ALL
SELECT r.Pos, r.stock_date, r.Row_ID, r.change, GREATEST(s.total + r.change, 0) total
FROM SumFloor s
JOIN NumberedRows r ON (s.Pos + 1 = r.Pos))
SELECT *
FROM SumFloor
ORDER BY Pos
POS STOCK_DATE ROW_ID CHANGE TOTAL
---------- ---------- ------------------ ---------- ----------
1 01.01.18 AAQZtoAAAAAD9xeAAA 0 100
2 01.02.18 AAQZtoAAAAAD9xeAAB -10 90
3 01.03.18 AAQZtoAAAAAD9xeAAC 0 90
4 01.04.18 AAQZtoAAAAAD9xeAAD -90 0
5 01.05.18 AAQZtoAAAAAD9xeAAE -3 0
6 01.06.18 AAQZtoAAAAAD9xeAAF 15 15
7 01.07.18 AAQZtoAAAAAD9xeAAG -20 0
Had to remove the misleading stock column (not just for the negative values but the 90 to 80 change (from 5=5) was wrong too) and combine in/out into change to get a clearer picture. I also shifted the changes to the date whose total they affect.
can still be MERGEd I expect.
performance vs. model : my bet is on model.
regards,