Adding running total to union query

I posted this before and thought I had a solution. Unfortunately, it became 
too large and I received a "Query is too complex" error, so now I'd like to 
try a different approach...

I have created a Union Query to consolidate results from separate queries, 
each one of which represents results for a single month:

SELECT ReportMonth, MonthlyRev, MonthlyCost
FROM qryMonth1Total
UNION 
SELECT ReportMonth, MonthlyRev, MonthlyCost
FROM qryMonth2Total
UNION 
SELECT ReportMonth, MonthlyRev, MonthlyCost
FROM qryMonth3Total;
etc. (12 months total)

This gives me the following results:

ReportMonth      MonthlyRev      MonthlyCost
01/01/2007            $5000               $550
02/01/2007            $7500               $400
03/01/2007            $3500               $350
etc.

However, I would now like to add running sum columns to the union query, 
ideally resulting in this:

ReportMonth    MonthlyRev    MonthlyCost    MonthlyRevSum   MonthlyCostSum
01/01/2007          $5000             $550               $5000               
  $550
02/01/2007          $7500             $400             $12500                
 $950
03/01/2007          $3500             $350             $16000                
$1300
etc.

Is it possible to add this type of calculation to my existing union query, 
in a way that won't become so long that I can avoid the "query is too 
complex" error? (You can see my earlier post started 6/4 titled "Running Sum 
in Union Query" for the suggested answer that ultimately caused the error.) 

Please note that I'm relatively new to access (just started reading on 
subqueries today) so the simpler the better.
Thanks!
0
Utf
6/5/2007 9:57:02 PM
access.queries 6343 articles. 1 followers. Follow

2 Replies
947 Views

Similar Articles

[PageSpeed] 40

In article <CA964771-5CD1-4E5B-A94A-5998A831F8BA@microsoft.com>, 
SteveS@discussions.microsoft.com says...
> I posted this before and thought I had a solution. Unfortunately, it became 
> too large and I received a "Query is too complex" error, so now I'd like to 
> try a different approach...
> 
> I have created a Union Query to consolidate results from separate queries, 
> each one of which represents results for a single month:
> 
> SELECT ReportMonth, MonthlyRev, MonthlyCost
> FROM qryMonth1Total
> UNION 
> SELECT ReportMonth, MonthlyRev, MonthlyCost
> FROM qryMonth2Total
> UNION 
> SELECT ReportMonth, MonthlyRev, MonthlyCost
> FROM qryMonth3Total;
> etc. (12 months total)
> 
> This gives me the following results:
> 
> ReportMonth      MonthlyRev      MonthlyCost
> 01/01/2007            $5000               $550
> 02/01/2007            $7500               $400
> 03/01/2007            $3500               $350
> etc.
> 
> However, I would now like to add running sum columns to the union query, 
> ideally resulting in this:
> 
> ReportMonth    MonthlyRev    MonthlyCost    MonthlyRevSum   MonthlyCostSum
> 01/01/2007          $5000             $550               $5000               
>   $550
> 02/01/2007          $7500             $400             $12500                
>  $950
> 03/01/2007          $3500             $350             $16000                
> $1300
> etc.
> 
> Is it possible to add this type of calculation to my existing union query, 
> in a way that won't become so long that I can avoid the "query is too 
> complex" error? (You can see my earlier post started 6/4 titled "Running Sum 
> in Union Query" for the suggested answer that ultimately caused the error.) 
> 
> Please note that I'm relatively new to access (just started reading on 
> subqueries today) so the simpler the better.
> Thanks!
> 
Just a thought, does it have to be UNION?

These are examples for the Northwind sample database
that comes with Access. Paste each query into SQL View
of a new query and names the queries as below.  They are
merely examples.

Daily Sales Totals
-----------------
SELECT Orders.OrderDate, Sum([Order Subtotals].Subtotal) AS [Daily Sales]
FROM Orders INNER JOIN [Order Subtotals] ON Orders.OrderID=[Order 
Subtotals].OrderID
WHERE Orders.Orderdate BETWEEN [Enter start date:] AND [Enter end date:]
GROUP BY Orders.OrderDate;

Monthly Sales Totals
--------------------
SELECT Dateadd("m",Datediff("m",0,[d.OrderDate]),0) AS [Month], Sum(d.[Daily 
Sales]) AS [Monthly Sales], Count(d.OrderDate) AS [Business Days], CCur(Sum(d.
[Daily Sales])/Count(d.OrderDate)) AS [Daily Average]
FROM [Daily Sales Totals] AS d
GROUP BY Dateadd("m",Datediff("m",0,[d.OrderDate]),0);

Running Monthly Sales
----------------------
SELECT FORMAT(a.Month,"mmm-yyyy") AS [Month-Year], a.[Monthly Sales], SUM(b.
[Monthly Sales]) AS [Running Sales], COUNT(b.month) AS [Sales Months], DATEPART
("m",a.month) AS [Month Nbr], CCUR(SUM(b.[Monthly Sales])/DATEPART
("m",a.month)) AS [Monthly Average]
FROM [monthly sales totals] AS a INNER JOIN [monthly sales totals] AS b ON 
a.month>=b.month
GROUP BY a.month, a.[Monthly Sales]
ORDER BY a.Month;
0
Michael
6/6/2007 12:39:43 AM
Thanks Michael,

Each query only represents one month (for reasons I won't go into here...),
so that is why I would like to have the running sum within the union query.
The only other option (just thought of) is if I run a select query using the
union query as the source, and try to do the running sum there... but don't
know if that's even possible. Any other thoughts?

Steve

P.S. Does anybody know what's going on with the MS discussion group? It looks
like nothing is posting since about 2 days ago. I just happened to remember
that this site pulls from there and vice-versa.

Michael Gramelspacher wrote:
>> I posted this before and thought I had a solution. Unfortunately, it became 
>> too large and I received a "Query is too complex" error, so now I'd like to 
>[quoted text clipped - 41 lines]
>> subqueries today) so the simpler the better.
>> Thanks!
>
>Just a thought, does it have to be UNION?
>
>These are examples for the Northwind sample database
>that comes with Access. Paste each query into SQL View
>of a new query and names the queries as below.  They are
>merely examples.
>
>Daily Sales Totals
>-----------------
>SELECT Orders.OrderDate, Sum([Order Subtotals].Subtotal) AS [Daily Sales]
>FROM Orders INNER JOIN [Order Subtotals] ON Orders.OrderID=[Order 
>Subtotals].OrderID
>WHERE Orders.Orderdate BETWEEN [Enter start date:] AND [Enter end date:]
>GROUP BY Orders.OrderDate;
>
>Monthly Sales Totals
>--------------------
>SELECT Dateadd("m",Datediff("m",0,[d.OrderDate]),0) AS [Month], Sum(d.[Daily 
>Sales]) AS [Monthly Sales], Count(d.OrderDate) AS [Business Days], CCur(Sum(d.
>[Daily Sales])/Count(d.OrderDate)) AS [Daily Average]
>FROM [Daily Sales Totals] AS d
>GROUP BY Dateadd("m",Datediff("m",0,[d.OrderDate]),0);
>
>Running Monthly Sales
>----------------------
>SELECT FORMAT(a.Month,"mmm-yyyy") AS [Month-Year], a.[Monthly Sales], SUM(b.
>[Monthly Sales]) AS [Running Sales], COUNT(b.month) AS [Sales Months], DATEPART
>("m",a.month) AS [Month Nbr], CCUR(SUM(b.[Monthly Sales])/DATEPART
>("m",a.month)) AS [Monthly Average]
>FROM [monthly sales totals] AS a INNER JOIN [monthly sales totals] AS b ON 
>a.month>=b.month
>GROUP BY a.month, a.[Monthly Sales]
>ORDER BY a.Month;

0
SteveS
6/7/2007 3:40:52 PM
Reply:

Similar Artilces:

Adding Blank Rows after the last Detail of the Report
Hi All, I've used this code from Dwayne: Private Sub Report_Page() Dim intNumLines As Integer Dim intLineNumber As Integer Dim intTopMargin As Integer Dim ctl As Control Dim intLineHeight As Integer intNumLines = 12 intTopMargin = Me.Section(3).Height intLineHeight = Me.Section(0).Height For Each ctl In Me.Section(0).Controls For intLineNumber = 0 To intNumLines - 1 Me.Line (ctl.Left, intTopMargin + _ (intLineNumber * intLineHeight)) - _ Step(ctl.Width, intLineHeight), , B Next Next End Sub My report needs to print blank rows (at least...

Adding hyperlinks with parameters
Hey everybody I have a batch file which needs to be run from an excel sheet with a parameter, like this: c:\1.bat myParameter But when i try to run the Hyperlink, the Excel shows an error message saying it can't open the specified file (probably because the is a space between the file and the parameter) is there any known way to run the link from the excel? On Mar 2, 12:45=A0pm, Pasha <pavel_v...@mailto.mod.gov.il> wrote: > Hey everybody > I have a batch file which needs to be run from an excel sheet with a > parameter, like this: > c:\1.bat myParameter > But when i ...

outlook vcard, ad integration user properties
my boss is trying to get hix fax# in his vcard. he is using his address from the global address list I have modified his profile in active directory users and computers: I go into AD users and computers, double click on his user, go to the telephones tab, and enter his fax #. but when I did this his fax # is still not being pulled up in his outlook vcard. Does anyone know where outlook is trying to get this field from / how i can get this field into his vcard? thx ...

ADDING A NUMBER
how do i add a number to a range of cells? I need to add 11.27 to a number of different cells each with a different number in them Put 11.27 in an empty cell, format it the same way as the numbers you want to add to, copy it, then select the numbers you want to add to and do edit>paste special and select add. -- Regards, Peo Sjoblom "Helpme" <Helpme@discussions.microsoft.com> wrote in message news:6D51344A-78E6-4377-B292-FC6C16FF6BA2@microsoft.com... > how do i add a number to a range of cells? I need to add 11.27 to a > number > of different cells e...

When adding attachments...
....in Outlook the following errors comes up: "Out of memory or system resources, please close some programs and try again" Quotas are fine. I have deinstalled/reinstalled Office, cleaned 'temp' areas, and many other tidbits. Any other ideas? Thanks. This might help as i had this problem with Outlook 98. Is the file you are trying to copy to attach nested in sub folders? if so try and copy the attachment to a root drive like c:\ Ignore previous email. wrong spellin if the attachment is nested in sub folders(this means you have to open different folders to get to ...

Masterpage Query
Hello Folks, I have many small items on the masterpage and find it can get quite frustrating sometimes when working on a document to have "This item is on the masterpage, to switch ..." all the time. Please can you tell me if it is possible to disable this message whilst still being able to view the masterpage items on screen. I know this is a long shot, but thought it would be worth a try anyway. Your help is and always has been very much appreciated. Thanking you in anticipation. -- Big Rick Hello Big Rick... Tools, options, User Assistance tab, uncheck Show tippages. -- ...

adding new records
I am totally new to CRM, so I hope this is really easy question: This concerns permissions.. I have a "sales" group, and with one of those people i need to be able to let them add new records on behalf of other "sales" people. Is there like a standard permission setting for it? (obviously every "sales" person can add new records if they select them selfs as the owner) thanks, Michal. Hi, By default the person who creates the record will be the owner. After record creation the person could reassign the record (manually) to another user. If all rec...

Picture Disappears When Added To Contact In Outlook 2003
Can someone help please. When I try to attach a picture to a contact in outlook 2003 immediately I double click the picture to be attached it disappears out of the outlook contact along with the placement holder in the form. Only when I right click the mouse and go remove picture do I get the placement holder back. I have looked at all the help menus but they offer no clues. Thanks TS ...

Top 5 SQL in an Aggregate Query
I'm counting occurrences for Questions Grouped by Market Mgr and 3 different Area Mgrs. Taking "Top 5" in the SQL statement brings in the overall Top 5 records, which it should. I could run code to examine each Area Mgr (w/ the Market Mgr), build a Top 5 and add to a Table after deleting all those Table's records prior to examining each Area Mgr. Or..is there another way?? Any possibiliity the "Grouping" in an Access Report would display only the Top 5 for each Area Mgr grouping? TIA - Bob See: Subquery Basics: TOP n records per group at: http://a...

Closing Dex utilities after running a macro
I have batch file that run a macro in the Dex utility, but the after the macro is finished the Utility is stays open. Is there a way to command or another way to get the dex utility to close? Re-record the macro -- I assume your macro builds the chunk file, etc. -- making sure you choose File -> Exit as your last step. Best regards, -- MG.- Mariano Gomez, MIS, MCP, PMP Maximum Global Business, LLC http://www.maximumglobalbusiness.com The Dynamics GP Blogster at http://dynamicsgpblogster.blogspot.com "Jason" wrote: > I have batch file that run a macro i...

Criteria Parameter in query for two fields: help
I have a form that utilizes two contact lists in separate combo boxes to illustrate projects that multiple people have worked on. I am trying to make it so that a report will illustrate the associated data based on these contacts. The selection will be based on either one contact (from either list) or both. Whereby on selection, the report will generate the associated data based on these user names. How would I go about creating a parameter in the query so that it will limit the content to reflect either contact list or a combination of the two? I am a beginner to Acc...

Adding ActiveX to dialog with wrapper
When I add an ActiveX object to a dialog using the dialog editor - right click - insert activeX object, the help on the resulting activex selection tool states that a wrapper will not be added by using this method. If you need a wrapper, it suggests using the class view. This is using Visual Studio 2005. I'm having some problems with this on an existing project. To make sure I understand the process, I created a new MFC project, added a dialog, created a class for that dialog and added a Flexgrid object using the right click method in the dialog. I then added a variable for the flexgrid...

Adding alternate columns
I work on a schedule where I record ticket count and ticket sales for each show, listed chronologically. Column A = week ending date Column B = # Tickets sold for April 5 show Column C = Ticket Revenue for April 5 show Column D = # Tickets sold for April 9 show Column E = Ticket Revenue for April 9 show Column F = # Tickets sold for April 12 show Column G = Ticket Revenue for April 12 show Column H = Total # Tickets sold for all shows Column I = Total Ticket Revenue for all shows In the Totals columns, the Total Tickets formula is "+B4+D4+F4", and the Total Revenue f...

Adding more than three Conditions to 'Conditional Formatting'
Can i add more than three conditions to the conditional formatting presets using code? Regards [Riz] -- Rizitsu ------------------------------------------------------------------------ Rizitsu's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=15840 View this thread: http://www.excelforum.com/showthread.php?threadid=320382 Riz, as you have found out, only 3 conditions with conditional formatting. But yes you can use some code to get more than 3, try this it will change the cell color in column A when you put in one ,two, three, or four, right click on the she...

A Simple Query problem?
I've wrestled with this one, but can't quite manage it! I have a tblStatement containing fields StatementID, Date, Description, and Value. For all records with Description = "NATWEST BANK", there are two values for each particular date. What I want to do is update the Description depending on whether the value is the Max or Min value for that particular date. I can use criteria with GroupBy and Min/Max in the query grid, but obviously cannot update the Description field as it is a GroupBy. And you won't be able to update anything if you use a GROUP BY or an ag...

Adding fields from a different query
I have a form built based on a main query. How do I add more fields on that form that come from a different query? Anne A couple possibilities... Change your first query to include the extra fields. Use your second query to "feed" a form, then embed that form as a subform on your main form. Good luck! Regards Jeff Boyce Microsoft Access MVP -- Disclaimer: This author may have received products and services mentioned in this post. Mention and/or description of a product or service herein does not constitute endorsement thereof. Any code or pseudoco...

Delimiter for adding Appointment in Entourage
Version: 2008 Operating System: Mac OS X 10.5 (Leopard) Processor: Power PC Email Client: Exchange What's the delimiter that Entourage uses if I want to add an appointment and the subject needs to be parsed by the Exchange server? <br><br>In Outlook, the hash/pound key (#) is used as delimiter. How about in Entourage 2008? <br><br>Basically, if I add an entry in a group calendar Out-Of-Office with the subject: #User1# On-Leave <br><br>in Outlook, this entry appears in the group calendar Out-Of-Office and also in User1's personal calendar. <...

Query Builder tool
Hi Anyone know Query Builder tool which can be used to build SQL Queries in MS Access and MS SQL Thanks, JohS On Thu, 7 Jun 2007 21:51:10 +0200, "JohS" <solimpnews@webmail.no> wrote: >Hi >Anyone know Query Builder tool which can be used to build SQL Queries in MS >Access and MS SQL >Thanks, JohS > ummm... other than the New Query window in Access??? John W. Vinson [MVP] "John W. Vinson" <jvinson@STOP_SPAM.WysardOfInfo.com> wrote in message news:5b3h639imt8jmo4m2a1cat2le84gdvu1lg@4ax.com... > On Thu, 7 Jun 2007 21:51:10...

Repointing Query = .xls filesize doubles?
I have an excel spreadsheet that is looking at 3 datasources, and has about 18 pivot tables and charts based around them. I recently renamed the tables that my .dqy files were looking at, but I changed them to look at the new table names.... When it refreshed data and I resaved it, my spreadsheet size grew from 76 mb to 166 mb. Anyone else suffer from this problem? How do I get rid of this information that isn't even being looked at anymore? Thanks for any help! ...

AD Monitoring
Is there a listing somewhere of what all components in AD should be minitored, thresholds, etc...we are evaluating a monitoring solution and need this information to take a decision on the product to use Hello Sameer, For performance start here: http://technet.microsoft.com/en-us/library/cc961943.aspx Also see: http://technet.microsoft.com/en-us/library/bb727046.aspx Use the included links from: http://technet.microsoft.com/en-us/library/cc739728(WS.10).aspx Best regards Meinolf Weber Disclaimer: This posting is provided "AS IS" with no warranties, and c...

Adding Terms & Conditions to the Quote Form
We have a client that would like to add their Terms & Conditions (T&C) text to the bottom of their GP Quotes. I've read that static text boxes in Report Designer can only be 80 characters, so that won't work as the T&C text is approximately 4-5 pages long. Does anyone have any suggestions on how to add this significant amount of text to a GP form? Thank you in advance. Scott No can do Scott - Report Writer is just not capable of this. The best solution is to purchase Accountable Software's Forms Printer - www.accountable.com. Frank Hamelly MCP-GP, MCT, MVP East...

Downloaded payees automatically added to payee list
Please tell me that in Money 2006, Microsoft has finally fixed the bug where the payees in my downloaded transactions are automatically added to my payee list (this despite the fact that I've checked off the option "Confirm new payees"). This alone would be worth the upgrade. On the subject of 2006, does anyone know if Microsoft added the cookie jar concept to accounts? The cookie jar allows you to squirrel money away within an account. TIA greg.block@gmail.com wrote: >Please tell me that in Money 2006, Microsoft has finally fixed the bug >where the payees in my downlo...

CRM 3 queries / software shortcomings? Help please.
We are looking to implement a CRM system at present, with emphasis on marketing. Having looked at the Microsoft offering there are certain areas that seem very weak. Would anyone with any experience of CRM 3 be able to make any suggestions regards the following: 1] According to an online Microsoft seminar the maximum number of emails that can be sent in one go is c.2,000. Or that is what they said it had been tested to (and passed). We need to send up to 20,000. 2] The whole email tracking seems weak. I understand that sent emails are recorded against the account/contact. B...

Adding Collapse/Expand to Publisher 2003 items
Hi I'm trying to enter a text box which may be expanded/Collapsed as follows: > More Info... > Next Item... > More Info... When you want bla bla bla, do bla bla bla, > Next Item... Can anyone tell me how to implement it?! Thank you 'bla bla bla' is the sound of geckos mating - so the naturalists tell me. No, you cannot do what you want. Your answer is rude & arrogant. I don't know why would anyone put you in a position to Accept calls for help. Besides - I don't believe it can't be done. Please don't call again "*...

running macro from 1 wks that manipulates another
I have been at this problem for too long...keep not getting the results I need. I have a wks (ie: wks1) that has a commandbutton on it that copies a 2nd wks (ie: wks2) to a 3rd (ie: wks3) so that I can delete some rows not needed for a report and re-sort based on data in 1 column. The copy procedure works fine but when it looks thru the data in column D for the string "series", it does not delete the rows. The secondary procedure to sort works fine. What am I doing wrong? Please Help...thx here is the code for both steps: Sub btnSortBySRC_Click() Dim strMainWks As Str...