Below is an example of how a running total can be derived in SQL:
--------------------------------------------------------
-- DDL for Table TABLE1
--------------------------------------------------------
DROP TABLE TABLE1;
CREATE TABLE "S2BDETL"."TABLE1"
(
"C1" VARCHAR2(20 BYTE),
"C2" NUMBER,
"C3" DATE
) ;
INSERT
INTO "S2BDETL"."TABLE1"
(
C1,
C2,
C3
)
VALUES
(
'A',
'1',
TO_DATE('2015-06-26 16:14:02', 'YYYY-MM-DD HH24:MI:SS')
);
INSERT
INTO "S2BDETL"."TABLE1"
(
C1,
C2,
C3
)
VALUES
(
'A',
'2',
TO_DATE('2015-06-29 16:14:22', 'YYYY-MM-DD HH24:MI:SS')
);
INSERT
INTO "S2BDETL"."TABLE1"
(
C1,
C2,
C3
)
VALUES
(
'A',
'2',
TO_DATE('2015-05-29 16:14:22', 'YYYY-MM-DD HH24:MI:SS')
);
INSERT
INTO "S2BDETL"."TABLE1"
(
C1,
C2,
C3
)
VALUES
(
'A',
'2',
TO_DATE('2015-04-29 16:14:22', 'YYYY-MM-DD HH24:MI:SS')
);
INSERT
INTO "S2BDETL"."TABLE1"
(
C1,
C2,
C3
)
VALUES
(
'A',
'2',
TO_DATE('2015-03-29 16:14:22', 'YYYY-MM-DD HH24:MI:SS')
);
INSERT
INTO "S2BDETL"."TABLE1"
(
C1,
C2,
C3
)
VALUES
(
'A',
'2',
TO_DATE('2015-02-29 16:14:22', 'YYYY-MM-DD HH24:MI:SS')
);
INSERT
INTO "S2BDETL"."TABLE1"
(
C1,
C2,
C3
)
VALUES
(
'A',
'2',
TO_DATE('2015-01-29 16:14:22', 'YYYY-MM-DD HH24:MI:SS')
);
INSERT
INTO "S2BDETL"."TABLE1"
(
C1,
C2,
C3
)
VALUES
(
'A',
'2',
TO_DATE('2014-12-29 16:14:22', 'YYYY-MM-DD HH24:MI:SS')
);
Without analytical functions:
SELECT SUM(TOTAL) running_Total,
B.C3,
A.c1
FROM
(SELECT SUM(C2) TOTAL,C1,C3 FROM TABLE1 GROUP BY C1,C3
) A,
(SELECT DISTINCT C3 FROM TABLE1
) B
WHERE A.C3 <= B.C3
GROUP BY B.C3,
a.c1;
Using analytical functions:
SELECT c1,
c3,
SUM(c2) OVER (PARTITION BY c1 ORDER BY c3 RANGE UNBOUNDED PRECEDING) running_total
FROM table1;