Skip to content
Advertisement

Query Oracle for 12 month moving total (SUM) of data

I need to run a query on some data that brings back the moving 12 month total. I’ve already performed the average function on the data… so now I just need to loop through and get a moving 12 month period of data and SUM it up so I can graph it.

Below is the current query i’m issuing but it isn’t adding up correctly. Basically I want to have January of 1996 show the SUM of the prior 12 months averaged data. So January of 1996 would be the sum of January 1995 + February 1995 …. all the way through December 1995. Then February of 1996 would be the SUM of February 1995 + March 1995 ….

Is this possible using the OVER function in Oracle 11g? Seems like it is but I’m not getting the right results for some reason.

Here is my current query:

Here is a few rows of the sample data and the current way the OVER function is calculating.

Here is a dataset incase that helps.

Thanks so much for any assistance! Josh

Advertisement

Answer

To get the desired result you need to order by year_dt column or combination of year_dt and month_dt columns:

When you are ordering only by month_dt the rows will be processed by analytic function in the following order:

producing result that doesn’t meet your expectations.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement