473,732 Members | 2,219 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calculate a Moving Average and Update Table

7 New Member
I am trying to calculate in VBA in Access 2002 a moving average and update a table with the calculations. Fields in my WeeklyData table are
Week Ending (date)
ItemNbr (double)
Sales Dollars (double)
Sales Units (double)
Promo (Text) -- is null or "X"
AvgWklyDollars (double)
AvgWklyUnits (double)

I have a vba module which I thought would work, but it doesn't. I think the problem is an embedded SQL Totals Top 8 query, which doesn't work when I tried it as an Access query. HELP!

For each week and for each ItemNbr, I want to calculate the average of the Last 8 weeks, where Promo <> "X" . Where Promo Is Null I want to copy the prior week's averages. Finally, I want to update my table "WeeklySalesbyt ypeAllItems" with this calculated AvgWkly data.

Here's the code:

Expand|Select|Wrap|Line Numbers
  1. Function DateSQL(pvarDate) As String
  2. ' Create a string representation suitable for SQL
  3. ' Jet accepts only US dates or ISO dates
  4.  
  5.     If IsNull(pvarDate) Then
  6.         DateSQL = "Null"
  7.     Else
  8.         DateSQL = Format(pvarDate, "\#yyyy\-mm\-dd\#")
  9.     End If
  10.  
  11. End Function
  12.  
  13. Sub ComputeAllAverages()
  14. ' Calculate moving averages for sales and units in the weekly sales table
  15. ' A single total query is used to calculate both for each record
  16.  
  17.     Const SALES = "WeeklySalesbytypeAllItems"   
  18.     Const SCOPE = 8                           ' nb of weeks in moving average
  19.  
  20.     Dim mdb As DAO.Database
  21.     Dim recMain As DAO.Recordset
  22.     Dim recTot As DAO.Recordset
  23.     Dim strSQL As String
  24.  
  25.     Set mdb = CurrentDb
  26.     Set recMain = mdb.OpenRecordset(SALES, dbOpenDynaset)
  27.     Do Until recMain.EOF
  28.  
  29.         ' build query
  30.         strSQL _
  31.             = " SELECT" _
  32.             & " Count(*) AS Nb," _
  33.             & " Sum([Sales$]) AS TotalSales," _
  34.             & " Sum([Units]) AS TotalUnits" _
  35.             & " FROM (" _
  36.             & "     SELECT TOP " & SCOPE & " [Sales$], [Units]" _
  37.             & "     FROM [" & SALES & "]" _
  38.             & "     WHERE DPCI = " & recMain!ItemNbr_
  39.             & "     And [Week Ending] <= " & DateSQL(recMain![Week Ending]) _
  40.             & "     And Promo Is Null" _
  41.             & "     ORDER BY [Week Ending] Desc" _
  42.             & " ) AS WSAI"
  43.         Set recTot = mdb.OpenRecordset(strSQL, dbOpenSnapshot)
  44.  
  45.         ' store results
  46.         recMain.Edit
  47.         ' If recTot!Nb <> SCOPE Then   ' strict moving average
  48.         If recTot!Nb > 0 Then   ' lenient moving average
  49.             recMain!AvgWklyDollars = Null
  50.             recMain!AvgWklyUnits = Null
  51.         Else
  52.             recMain!AvgWklyDollars = recTot!TotalSales / recTot!Nb
  53.             recMain!AvgWklyUnits = recTot!TotalUnits / recTot!Nb
  54.         End If
  55.         recMain.Update
  56.  
  57.         recMain.MoveNext
  58.     Loop
  59. End Sub
  60.  
Here's sample data from the WeeklySalesbyty peAllItems table.

ItmNbr Week Ending Sales$ Units Promo
10025 9/15/2007 11349 2229
10025 9/22/2007 13593 2729
10025 9/29/2007 12709 2556
10025 10/6/2007 10104 1911
10025 10/13/2007 8693 1586
10025 10/20/2007 8712 1589
10025 10/27/2007 8532 1552
10025 11/3/2007 9553 1733
10025 11/10/2007 9713 1765
10025 11/17/2007 14827 2918
10025 11/24/2007 13938 2802 X
10025 12/1/2007 14102 2836 X
10025 12/8/2007 11052 2090
10025 12/15/2007 12308 2274
10025 12/22/2007 11405 2112
10025 12/29/2007 12624 2489
10025 1/5/2008 11978 2412 X
10025 1/12/2008 11550 2325 X
10025 1/19/2008 9938 1875
10044 9/15/2007 4211 4265
10044 9/22/2007 3965 4017
10044 9/29/2007 4124 4180
10044 10/6/2007 3388 3938
10044 10/13/2007 3768 3816
10044 10/20/2007 3881 3934
10044 10/27/2007 3692 3742
10044 11/3/2007 3654 3702
10044 11/10/2007 3429 3475 X
10044 11/17/2007 3756 3809
10044 11/24/2007 3869 3925
10044 12/1/2007 4308 4367
10044 12/8/2007 4490 4553
10044 12/15/2007 5516 5592
10044 12/22/2007 8016 8119
10044 12/29/2007 5097 5169
10044 1/5/2008 3608 3661
10044 1/12/2008 4121 4179 X
10044 1/19/2008 4259 4317
Mar 4 '08 #1
0 4638

Sign in to post your reply or Sign up for a free account.

Similar topics

6
9478
by: Stephen Miller | last post by:
Firstly, sorry for the long post, but I've included a fair bit of sample data. Im doing a comparision of 10yr Bond prices and CPI adjustments, with an 18 week moving average of the CPI. I'm using a nested sub-query to calculate the moving average, but I'm having difficulty selecting exactly 18 data points (ie When I include the 'HAVING COUNT(C1.Closes) = 18' line, I get no results). Can anyone help?
2
13604
by: Wayne Aprato | last post by:
I've read most, if not all, of the posts on moving average and still can't find a simple solution to my problem (if a simple solution exists!) I have a table with 2 fields: Hours and Injuries. I have a query based on this table which shows these 2 fields and calculates a third field: Frequency Rate, based on a formula which uses the Hours and Injuries fields. Is there a simple way of A: using yet another calculated field in the query...
4
6374
by: Rich_C | last post by:
I'm sure this is very simple, but I have very little experience with javascript -- and what I do know isn't helping me here. I have a simple form where users can enter a quantity (qty) and cost (cost). Users can dynamically add rows to the table so I don't know how many rows might need to be calculated. I need to calculate the total (qty * cost) and put that number in a table cell (or read only input box). I also need to sum the...
2
6164
by: mscdex | last post by:
I have a server application that accepts file transfers (utilitzing tcplistener) and was wondering how I would efficiently go about determining the calculate transfer rate while I am transferring the file. The Sub where the transfer actually takes place is called asynchronously. The (psuedo) code in the Sub goes something like this: While byteCount < filesize bytesRead = Bytes read from NetworkStream
4
6538
by: gaga | last post by:
hi guys, a part of my program requires me to calculate an average of items that are sold. the easiest way to do that would be writing a function, but im having trouble making up the parameters. if you can point me which elements to use when performing such a task, i would really appreciate it. thanks
7
20134
by: fjm | last post by:
Hi all, I have a problem getting a correct result with my sql code and figured I would see if anybody could help. I have two fields in a table that have timestamps. I want to find the difference in time between the two stamps and then calculate the average. Here is the code that I have come up with so far. SELECT AVG(TIMEDIFF(departure_Time, arrival_Time)) as average FROM t1 WHERE employee_Number= '3'
3
10915
by: paeh | last post by:
hello..can anyone help me. I am beginner in programming. I need to make a system that can calculate moving average. my system process will be executed according to certain schedule such as daily, weekly or monthly based on the data in the database. The moving average will then be recorded for further process. I want to know what is the software should be use to develop it? and can anyone show me a simple coding to calculate moving...
1
7631
by: Michel | last post by:
Hello, I need to calculate moving averages of weekly data during the last year. After some search, I believe that the best approach will be to get a dataset from the SQL Server database, browse the records and, using an algorithm, calculate the moving average. There is an article on the "Code Project" website entitled "A Simple Moving Average Algorithm" but honnestly I have been unable to
12
9143
by: denveromlp | last post by:
Hello, I'm new to Access and trying to calculate a rolling 12 month average from some time data. Each data point is a date and a measurement taken at that date. As far as I can tell, the only way to take the rolling average is to create a make-table of all the data points within the last year. Then create a query to pull out the minimum date, create a second query to pull out the maximum date, create a thrid query to pull out the...
0
8774
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9447
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9307
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.