Links

   Quran Explorer - Interactive Audio Recitations & Translations

Friday, November 15, 2013

Oracle and Postgres Cummulative Sum aka Running Totals


Hello Random Googler !!!

You landed here today... u r welcome.

Now consider the following output.

The 'interesting' column is the last one

NameDateAmountCumulative Sum
Mike01-JUN-1310001000
John01-JUN-1310002000
Omar01-JUL-1310003000
Shamim01-JUL-1310004000
Abdul01-JUL-1310005000
Jim01-AUG-1310006000
ZeGuru05-SEP-1310007000
Duli06-OCT-1310008000


Another example
(grouped by date... sorry partitioned by date)


NameDateAmountCumulative Sum
Mike01-JUN-1310001000
John01-JUN-1310002000
Omar01-JUL-1310001000
Shamim01-JUL-1310002000
Abdul01-JUL-1310003000
Jim01-AUG-1310001000
ZeGuru05-SEP-1310001000
Duli06-OCT-1310001000

The first one was achieved by;

SELECT name, date, amount, sum(amount) over(order by payment_id) cummulative_sum
FROM vw_payment

THE second was achieved by;

SELECT name, date, amount, sum(amount) over(partition by date, order by payment_id) cummulative_sum
FROM vw_payment

(the partition by clause was used to restart the running totals for each date)


do i need to say that payment_id is just the PK (incremental/serial integer) of the original table ?

By the way this works for both PostgreSQL and Oracle

Again u r welcome

No comments:

Post a Comment

Feel free to leave a comment