473,587 Members | 2,494 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Automating Query to use input values (array)

7 New Member
Hi,

I am trying to automate the running of a SQL Query. I have a Table in Access 2003 that contains records with several fields, (member identifier, $ amount and months during the year they were members). I want to create a "histogram" of sorts to count and sum the information depending on which bucket the $ amount falls in. For example all members with $ amount between 0 and $1, all members between $1 and $100, etc. The two Queries I have written do this in steps, and currently prompts me to enter the Min and Max values. The first query is a Select Query that creates a Table of all records that fall betwqeen the Min and Max. The second Query then collapses the data to Sum the $ amount and count the members. I then copy the result into an Excel spreadsheet.

How can I automate this process so that I can have the Queries run automatically using as an input an array of Min and Max pairs? I'd also like the output of each run to be automatically (and successively) stored in an Excel Worksheet.

Here are the SQL Queries I have written:
The first is called CLT and creates a Table used by the second
Expand|Select|Wrap|Line Numbers
  1. SELECT [15B].[Member ID], [15B].[Total], [15B].[Member Months], [min $ ?] AS [MIN], [max $ ?] AS [MAX]
  2. FROM 15B
  3. WHERE ((([15B].[Total])>=[min $ ?] And ([15B].[Total])<[max $ ?]));
  4.  
and the second query:
Expand|Select|Wrap|Line Numbers
  1. SELECT [CLT].MIN, [CLT].MAX, Count(NZ([CLT].[Member ID])) AS [CountOfMember ID], Sum([CLT].[Total]) AS [SumOfTotal]
  2. FROM CLT
  3. GROUP BY [CLT].MIN, [CLT].MAX;
  4.  

I have been trying to use VBA scripts, but have not been successful. Any advice would be appreciated,
Wil
Mar 23 '07 #1
18 3741
Rabbit
12,516 Recognized Expert Moderator MVP
Hi,

I am trying to automate the running of a SQL Query. I have a Table in Access 2003 that contains records with several fields, (member identifier, $ amount and months during the year they were members). I want to create a "histogram" of sorts to count and sum the information depending on which bucket the $ amount falls in. For example all members with $ amount between 0 and $1, all members between $1 and $100, etc. The two Queries I have written do this in steps, and currently prompts me to enter the Min and Max values. The first query is a Select Query that creates a Table of all records that fall betwqeen the Min and Max. The second Query then collapses the data to Sum the $ amount and count the members. I then copy the result into an Excel spreadsheet.

How can I automate this process so that I can have the Queries run automatically using as an input an array of Min and Max pairs? I'd also like the output of each run to be automatically (and successively) stored in an Excel Worksheet.

Here are the SQL Queries I have written:
The first is called CLT and creates a Table used by the second
Expand|Select|Wrap|Line Numbers
  1. SELECT [15B].[Member ID], [15B].[Total], [15B].[Member Months], [min $ ?] AS [MIN], [max $ ?] AS [MAX]
  2. FROM 15B
  3. WHERE ((([15B].[Total])>=[min $ ?] And ([15B].[Total])<[max $ ?]));
  4.  
and the second query:
Expand|Select|Wrap|Line Numbers
  1. SELECT [CLT].MIN, [CLT].MAX, Count(NZ([CLT].[Member ID])) AS [CountOfMember ID], Sum([CLT].[Total]) AS [SumOfTotal]
  2. FROM CLT
  3. GROUP BY [CLT].MIN, [CLT].MAX;
  4.  

I have been trying to use VBA scripts, but have not been successful. Any advice would be appreciated,
Wil
What are the VBA scripts you have tried to use? Can you post the code?
Mar 23 '07 #2
WilhelmAccess
7 New Member
I guess I should have said "I'd like to use VBA scripts", because they seem like they could handle the approach. I don't have any VBA scripts - only the SQL queries shown above.

Thanks,
Wil
Mar 23 '07 #3
Rabbit
12,516 Recognized Expert Moderator MVP
How are these min/max pairs coming about? Are they chosen by the user or are they constant?
Mar 23 '07 #4
WilhelmAccess
7 New Member
They are constant. Right now when I run the Select query I enter them by hand. However, I have them stored in a Table and would like to automate the process. Here is the table:

Min Max
($20,000,000.00 ) ($0.01)
$0.00 $1.00
$1.00 $250.00
$250.00 $1,000.00
$1,000.00 $2,500.00
$2,500.00 $5,000.00
$5,000.00 $10,000.00
$10,000.00 $15,000.00
$15,000.00 $20,000.00
$20,000.00 $25,000.00
$25,000.00 $30,000.00
$30,000.00 $35,000.00
$35,000.00 $40,000.00
$40,000.00 $45,000.00
$45,000.00 $50,000.00
$50,000.00 $55,000.00
$55,000.00 $60,000.00
$60,000.00 $65,000.00
$65,000.00 $70,000.00
$70,000.00 $75,000.00
$75,000.00 $80,000.00
$80,000.00 $85,000.00
$85,000.00 $90,000.00
$90,000.00 $95,000.00
$95,000.00 $100,000.00
$100,000.00 $150,000.00
$150,000.00 $200,000.00
$200,000.00 $250,000.00
$250,000.00 $300,000.00
$300,000.00 $350,000.00
$350,000.00 $400,000.00
$400,000.00 $450,000.00
$450,000.00 $500,000.00
$500,000.00 $750,000.00
$750,000.00 $1,000,000.00
$1,000,000.00 $2,000,000.00
$2,000,000.00 $200,000,000.00


Thanks,
Wil
Mar 23 '07 #5
ADezii
8,834 Recognized Expert Expert
Hi,

I am trying to automate the running of a SQL Query. I have a Table in Access 2003 that contains records with several fields, (member identifier, $ amount and months during the year they were members). I want to create a "histogram" of sorts to count and sum the information depending on which bucket the $ amount falls in. For example all members with $ amount between 0 and $1, all members between $1 and $100, etc. The two Queries I have written do this in steps, and currently prompts me to enter the Min and Max values. The first query is a Select Query that creates a Table of all records that fall betwqeen the Min and Max. The second Query then collapses the data to Sum the $ amount and count the members. I then copy the result into an Excel spreadsheet.

How can I automate this process so that I can have the Queries run automatically using as an input an array of Min and Max pairs? I'd also like the output of each run to be automatically (and successively) stored in an Excel Worksheet.

Here are the SQL Queries I have written:
The first is called CLT and creates a Table used by the second
Expand|Select|Wrap|Line Numbers
  1. SELECT [15B].[Member ID], [15B].[Total], [15B].[Member Months], [min $ ?] AS [MIN], [max $ ?] AS [MAX]
  2. FROM 15B
  3. WHERE ((([15B].[Total])>=[min $ ?] And ([15B].[Total])<[max $ ?]));
  4.  
and the second query:
Expand|Select|Wrap|Line Numbers
  1. SELECT [CLT].MIN, [CLT].MAX, Count(NZ([CLT].[Member ID])) AS [CountOfMember ID], Sum([CLT].[Total]) AS [SumOfTotal]
  2. FROM CLT
  3. GROUP BY [CLT].MIN, [CLT].MAX;
  4.  

I have been trying to use VBA scripts, but have not been successful. Any advice would be appreciated,
Wil
Here is a basic Code Template that you can adapt to your own specific needs in
order to automate your 'Query Creation Process', It assumes the following:
__1. tblMinMax
[Min] (CURRENCY)
[Max] (CURRENCY)
__2. tblMemberData
[Member ID] (AUTO - PK)
[Total] (CURRENCY)
[Member Months] (TEXT)
Expand|Select|Wrap|Line Numbers
  1. Dim MyDB As DAO.Database, rsMinMax As DAO.Recordset
  2. Dim strSQL As String, rsResult As DAO.Recordset
  3.  
  4. Set MyDB = CurrentDb()
  5.  
  6. 'rsMinMax will consist of all Min/Max pairs in tblMinMax
  7. Set rsMinMax = MyDB.OpenRecordset("tblMinMax", dbOpenSnapshot)
  8.  
  9. rsMinMax.MoveFirst
  10.  
  11. Do While Not rsMinMax.EOF
  12.   strSQL = "SELECT * FROM tblMemberData WHERE [Total] Between " & rsMinMax![Min] & " And " & rsMinMax![Max] & ";"
  13.   Set rsResult = MyDB.OpenRecordset(strSQL, dbOpenSnapshot)
  14.     rsResult.MoveFirst
  15.     'processing goes here for each Min/Max pair
  16.   rsMinMax.MoveNext
  17. Loop
  18.  
  19. rsMinMax.Close
  20. rsResult.Close
Mar 24 '07 #6
WilhelmAccess
7 New Member
Hi ADezii,

Thanks for the code snippet. I have added it it to a function, and am still having trouble with the second part of my processing. I have modified your snippet to run the first query(with the fields I am interested in), but I still need to run a second Query to Sum and Count. Can I operate on rsResult as if it were a Table? Please look at the following code to see what I have attempted:

Expand|Select|Wrap|Line Numbers
  1. Function GenContTbl(tblMinMax, MemberTbl, File_Name) As Integer
  2. '?GenContTbl("CTRanges", "15A", "C:\crap\test2.txt")
  3. Dim MyDB As DAO.Database, rsMinMax As DAO.Recordset
  4. Dim strSQL As String, strSQL2 As String, rsResult As DAO.Recordset, rsResult2 As DAO.Recordset
  5. Dim line
  6.  
  7. Set MyDB = CurrentDb()
  8.  
  9. 'rsMinMax will consist of all Min/Max pairs in tblMinMax
  10. Set rsMinMax = MyDB.OpenRecordset(tblMinMax, dbOpenSnapshot)
  11.  
  12. rsMinMax.MoveFirst
  13.  
  14. Do While Not rsMinMax.EOF
  15.   'strSQL = "SELECT * FROM 15A WHERE [Total Allowed Claims] Between " & rsMinMax![Min] & " And " & rsMinMax![Max] & ";"
  16.   strSQL = "SELECT [Member ID], [Total Allowed Claims], [Member Months] FROM 15A WHERE [Total Allowed Claims] Between " & rsMinMax![Min] & " And " & rsMinMax![Max] & ";"
  17.   Set rsResult = MyDB.OpenRecordset(strSQL, dbOpenSnapshot)
  18.     rsResult.MoveFirst
  19.  
  20.   'strSQL2 = "SELECT [CLT].MIN, [CLT].MAX, Count(NZ([CLT].[Member ID])) AS [CountOfMember ID], Sum([CLT].[Total Allowed Claims]) AS [SumOfTotal Allowed Claims]" FROM CLT GROUP BY [CLT].MIN, [CLT].MAX;
  21.   strSQL2 = "SELECT Count(NZ([Member ID])) AS [CountOfMember ID]FROM rsResult;"
  22.   Set rsResult2 = MyDB.OpenRecordset(strSQL2, dbOpenSnapshot)
  23.  
  24.     'processing goes here for each Min/Max pair
  25.  
  26.   rsMinMax.MoveNext
  27. Loop
  28.  
  29. rsMinMax.Close
  30. rsResult.Close
  31.  
  32. End Function
  33.  
Is it possible to examine rsResult and rsReult2 in the debugger as I step through the code?

Secondly, I would like to somehow store the result of the second query - preferebly as a record in a new table, which I would then output to excel.

Lastly, I am running into an error situation when the first query finds zero records. Is there an easy way around that?

Thanks much,
Wil
Mar 24 '07 #7
ADezii
8,834 Recognized Expert Expert
Hi ADezii,

Thanks for the code snippet. I have added it it to a function, and am still having trouble with the second part of my processing. I have modified your snippet to run the first query(with the fields I am interested in), but I still need to run a second Query to Sum and Count. Can I operate on rsResult as if it were a Table? Please look at the following code to see what I have attempted:

Expand|Select|Wrap|Line Numbers
  1. Function GenContTbl(tblMinMax, MemberTbl, File_Name) As Integer
  2. '?GenContTbl("CTRanges", "15A", "C:\crap\test2.txt")
  3. Dim MyDB As DAO.Database, rsMinMax As DAO.Recordset
  4. Dim strSQL As String, strSQL2 As String, rsResult As DAO.Recordset, rsResult2 As DAO.Recordset
  5. Dim line
  6.  
  7. Set MyDB = CurrentDb()
  8.  
  9. 'rsMinMax will consist of all Min/Max pairs in tblMinMax
  10. Set rsMinMax = MyDB.OpenRecordset(tblMinMax, dbOpenSnapshot)
  11.  
  12. rsMinMax.MoveFirst
  13.  
  14. Do While Not rsMinMax.EOF
  15.   'strSQL = "SELECT * FROM 15A WHERE [Total Allowed Claims] Between " & rsMinMax![Min] & " And " & rsMinMax![Max] & ";"
  16.   strSQL = "SELECT [Member ID], [Total Allowed Claims], [Member Months] FROM 15A WHERE [Total Allowed Claims] Between " & rsMinMax![Min] & " And " & rsMinMax![Max] & ";"
  17.   Set rsResult = MyDB.OpenRecordset(strSQL, dbOpenSnapshot)
  18.     rsResult.MoveFirst
  19.  
  20.   'strSQL2 = "SELECT [CLT].MIN, [CLT].MAX, Count(NZ([CLT].[Member ID])) AS [CountOfMember ID], Sum([CLT].[Total Allowed Claims]) AS [SumOfTotal Allowed Claims]" FROM CLT GROUP BY [CLT].MIN, [CLT].MAX;
  21.   strSQL2 = "SELECT Count(NZ([Member ID])) AS [CountOfMember ID]FROM rsResult;"
  22.   Set rsResult2 = MyDB.OpenRecordset(strSQL2, dbOpenSnapshot)
  23.  
  24.     'processing goes here for each Min/Max pair
  25.  
  26.   rsMinMax.MoveNext
  27. Loop
  28.  
  29. rsMinMax.Close
  30. rsResult.Close
  31.  
  32. End Function
  33.  
Is it possible to examine rsResult and rsReult2 in the debugger as I step through the code?

Secondly, I would like to somehow store the result of the second query - preferebly as a record in a new table, which I would then output to excel.

Lastly, I am running into an error situation when the first query finds zero records. Is there an easy way around that?

Thanks much,
Wil
'Insert this line for the Summation of [Total] for a given Min/Max combination as indicated in the code below (code window):
Debug.Print DSum("[Total]", "tblMemberData" , "[Total] Between " & rsMinMax![Min] & " And " & rsMinMax![Max])
Expand|Select|Wrap|Line Numbers
  1. Dim MyDB As DAO.Database, rsMinMax As DAO.Recordset
  2. Dim strSQL As String, rsResult As DAO.Recordset
  3.  
  4. Set MyDB = CurrentDb()
  5.  
  6. 'rsMinMax will consist of all Min/Max pairs in tblMinMax
  7. Set rsMinMax = MyDB.OpenRecordset("tblMinMax", dbOpenSnapshot)
  8.  
  9. rsMinMax.MoveFirst
  10.  
  11. Do While Not rsMinMax.EOF
  12.   strSQL = "SELECT * FROM tblMemberData WHERE [Total] Between " & rsMinMax![Min] & " And " & rsMinMax![Max] & ";"
  13.   Set rsResult = MyDB.OpenRecordset(strSQL, dbOpenSnapshot)
  14.   rsResult.MoveFirst
  15.     '----------------------------- Insertion Here -----------------------------
  16.   Debug.Print DSum("[Total]", "tblMemberData", "[Total] Between " & rsMinMax![Min] & " And " & rsMinMax![Max])
  17.  
  18.     'processing goes here for each Min/Max pair
  19.   rsMinMax.MoveNext
  20. Loop
  21.  
  22. rsMinMax.Close
  23. rsResult.Close
Mar 24 '07 #8
WilhelmAccess
7 New Member
Thanks for the Debug statement. It is very helpful.

Is there a way to run my second query on the resultant "rsResult"?

Thanks in advance,
Wil
Mar 24 '07 #9
ADezii
8,834 Recognized Expert Expert
Thanks for the Debug statement. It is very helpful.

Is there a way to run my second query on the resultant "rsResult"?

Thanks in advance,
Wil
You seem to be unlucky in that you caught the least skilled Moderator/Expert as far as SQL goes. From what I see, you cannot Open the Query from the Recordset (rsResult) itself but you can utilize the SQL String used to create the Rercordset, namely strSQL. You cannot use the RunSQL or Execute Methods since they are reserved for Action Queries. What you can do, and this is a far stretch, is create a QueryDef (Query) Object based on the SQL and then Open the Query. The code below will illustrate the point I am making.


Expand|Select|Wrap|Line Numbers
  1. Dim qdf As QueryDef, qdf2 As QueryDef
  2. 'If the Query Exists, it must be Deleted or an Error will occur
  3. For Each qdf2 In CurrentDb.QueryDefs
  4.   If qdf2.Name = "MyQuery" Then
  5.     CurrentDb.QueryDefs.Delete qdf2.Name
  6.   End If
  7. Next
  8.  
  9. 'Create the QueryDef, in your case from strSQL
  10. Set qdf = CurrentDb.CreateQueryDef("MyQuery", "SELECT * FROM Employees WHERE [LastName] Like 'Bu*'")
  11.  
  12. 'Open the Query
  13. DoCmd.OpenQuery "MyQuery", acViewNormal, acReadOnly
NOTE: Please do not go crazy trying to implement this logic. As previously stated, I can almost guarantee that more skilled members will come up with a more viable solution, but for now it is an alternative.
Mar 25 '07 #10

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

Similar topics

2
14123
by: davidv | last post by:
I am building a very simple form that takes text and inserts data in a MySQL db. I would like my "logic" to simply insert the value in to the field in the database that matches the name from the query string. Here's the question- can I do this if I do not know how many name/value pairs are passed to the "logic" ? Can I just step through the $_POST array and use a do while $i <= count($_POST) or something?
3
1940
by: Nick Truscott | last post by:
<? // scoreinput.php - input a match score when match selected from list ?> <html> <head> <basefont face="Verdana"> </head> <body>
3
1958
by: cover | last post by:
I have a table with 50 fields that receive input depending on whether that input came in from a 'shaker' form or a 'conveyor' form. Input from the 'conveyor' form might populate 25 fields while input from the 'shaker' form will populate another 20-25 fields but not the same fields (however there are about 10 common fields to both). I'd thought about using two tables (one for 'conveyor' and the other for 'shaker') but thought I'd try just...
10
2843
by: Jaye | last post by:
Hi. I am a relative newbie to ASP and I am working on an application that uses ASP and an Oracle 9i database. I have a form that allows the user to query the database by selecting a client name(s) from a listbox and also set a time period for the search by selecting a start date and end date. Once the query is executed a form letter(s) is (are) generated to the client(s) that details the products that have been purchased during the time...
5
7430
stepterr
by: stepterr | last post by:
I have a form that is built based on a query. Everything is working except when I submit the form the radio buttons are only updating the first row in my database. dcategory and dthumbnail are two radio buttons that I have for each one of the rows in the table. I've tried using a hidden input object for each of the radio button groups to store the values in but clearly I'm having a mental block because I can't get that to work right either. So...
4
6489
by: TechnoAtif | last post by:
Hi ALL I have entered some array values using checkboxes into mysql database through a form. Next iam creating a searchpage where all those cateogories inserted through checkboxes has to be retrieved using list/menu box. When i check only a single checkbox to insert the checked category ,selecting that category through list box gives out the entire data of the user corresponding to that category. However when i check multiple checkboxes and...
4
4567
by: zion4ever | last post by:
Hello good people, Please bear with me as this is my first post and I am relative new to ASP. I do have VB6 experience. I have a form which enables users within our company to do an intranet reservation of available resources (laptops, beamers, etc). The MySql database queries are already in place, as is the ASP administration panel. The frontend that users will see however, still needs some work. I'm really close, but since I'm no...
0
1279
by: totomalas | last post by:
I have developed a report in Access 2007 that runs on three queries, each promting an input from the user...this report is used for a meeting and it should be printed nine times...what I do now is open the report nine times, with each print i enter the same inputs for the first two queries and a different input for the third one...so this is becoming a hassle for me.. :( Query1 takes the meeting date Query2 takes the budget date Query3...
5
2882
by: totomalas | last post by:
I have developed a report in Access 2007 that runs on three queries, each promting an input from the user...this report is used for a meeting and it should be printed nine times...what I do now is open the report nine times, with each print i enter the same inputs for the first two queries and a different input for the third one...so this is becoming a hassle for me.. :( Query1 takes the meeting date Query2 takes the budget date Query3...
0
7924
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7854
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
8349
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...
1
7978
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8221
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6629
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
5722
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
5395
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2364
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

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.