I need my running sum to work for more than one year. It works great
but then starts over when the year starts over. My example here is
straight from the Northwind database. I want a runningg sum of the
freight but for some reason it does a running sum for each year.
Anybody know how I can get it to keep running no matter the year.
thanks!
SELECT DatePart("yyyy" ,[orderdate]) AS ayear, DatePart("m",[orderdate])
AS amonth, Sum(Orders.Frei ght) AS SumOfFreight,
Format(DSum("Fr eight","Orders" ,"DatePart ('yyyy', [OrderDate])<=" &
[Ayear] & " and DatePart('m', [OrderDate])<=" & [Amonth] &
""),"$0,000.00" ) AS RunTot, Format([orderdate],"mmm") AS fdate
FROM Orders
GROUP BY DatePart("yyyy" ,[orderdate]), DatePart("m",[orderdate]),
Format([orderdate],"mmm")
ORDER BY DatePart("yyyy" ,[orderdate]), DatePart("m",[orderdate]),
Format([orderdate],"mmm"); 9 2598
"turtle" <ko****@vistaco ntrols.com> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com... I need my running sum to work for more than one year. It works great but then starts over when the year starts over. My example here is straight from the Northwind database. I want a runningg sum of the freight but for some reason it does a running sum for each year. Anybody know how I can get it to keep running no matter the year. thanks!
SELECT DatePart("yyyy" ,[orderdate]) AS ayear, DatePart("m",[orderdate]) AS amonth, Sum(Orders.Frei ght) AS SumOfFreight, Format(DSum("Fr eight","Orders" ,"DatePart ('yyyy', [OrderDate])<=" & [Ayear] & " and DatePart('m', [OrderDate])<=" & [Amonth] & ""),"$0,000.00" ) AS RunTot, Format([orderdate],"mmm") AS fdate FROM Orders GROUP BY DatePart("yyyy" ,[orderdate]), DatePart("m",[orderdate]), Format([orderdate],"mmm") ORDER BY DatePart("yyyy" ,[orderdate]), DatePart("m",[orderdate]), Format([orderdate],"mmm");
Grouping or sorting on a calculated column is bad for performance because
the query optimizer cannot make use of an index on the orderdate column if
one exists. Instead make a calendar table to hold all the months you are
ever likely to need, then join to this table in your query.
This code snippet will build and populate the calendar table.
'-------------------------------------------------------
Sub FillMonths()
Dim iMonth As Integer
Dim iYear As Long
Dim iDate As Date
Dim strSQL As String
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
On Error GoTo HandleErr
Set dbs = CurrentDb()
strSQL = "create table months(monthSta rt datetime not null " _
& "constraint PK_monthStart primary key, " _
& "monthEnd datetime not null constraint IX_monthEnd unique)"
dbs.Execute strSQL
' fill the month table with months from 1990-Jan-01 to 2020-Dec-31
Set rst = dbs.OpenRecords et("months", dbOpenTable, dbAppendOnly)
For iYear = 1990 To 2020
For iMonth = 1 To 12
iDate = CDate(iMonth & "/1/" & iYear) ' US format
rst.AddNew
rst("monthStart ") = iDate
rst("monthEnd") = DateAdd("m", 1, iDate) - 1
rst.Update
Next iMonth
Next iYear
ExitHere:
On Error Resume Next
rst.Close
Set rst = Nothing
Set dbs = Nothing
On Error GoTo 0
Exit Sub
HandleErr:
MsgBox (Err.Descriptio n)
Resume ExitHere
End Sub
'------------------------------------------
Then you query becomes something like this:
select format$(m.month Start,"mmm-yyyy") as month,
(
select sum(o2.Freight)
from orders as o2
where o2.OrderDate >= m.monthStart
and o2.OrderDate < m.monthEnd
) as SumOfFreight,
(
select sum(o2.Freight)
from orders as o2
where o2.OrderDate < m.monthEnd
) as RunTot
from months as m
order by m.monthStart
I created an Orders table:
OrderID OrderDate Freight
1 1/5/99 $25.00
2 2/24/00 $15.50
3 3/17/01 $22.00
4 12/17/01 $33.44
5 4/5/02 $222.00
6 5/5/03 $333.00
7 6/6/04 $444.00
8 7/7/04 $3.60
I then pasted in the same query and got:
ayear amonth SumOfFreight RunTot fdate
1999 1 $25.00 $0,025.00 Jan
2000 2 $15.50 $0,040.50 Feb
2001 3 $22.00 $0,062.50 Mar
2001 12 $33.44 $0,095.94 Dec
2002 4 $222.00 $0,284.50 Apr
2003 5 $333.00 $0,627.50 May
2004 6 $444.00 $1,061.50 Jun
2004 7 $3.60 $1,065.10 Jul
So the fifth result adds $222.00 to $62.50 ignoring month 12 because
it's past month 4. The basic idea is correct except that their logic
for comparing dates is wacky.
I created the following function:
Public Function CompareDates(dt 1 As Date, dt2 As Date) As Integer
If Year(dt1) < Year(dt2) Then
CompareDates = -1
Exit Function
End If
If Year(dt2) < Year(dt1) Then
CompareDates = 1
Exit Function
End If
If Month(dt1) < Month(dt2) Then
CompareDates = -1
Exit Function
End If
If Month(dt2) < Month(dt1) Then
CompareDates = 1
Exit Function
End If
If Day(dt1) < Day(dt2) Then
CompareDates = -1
Exit Function
End If
If Day(dt2) > Day(dt1) Then
CompareDates = 1
Else
CompareDates = 0
End If
End Function
qryFixed:
SELECT DatePart("yyyy" ,[orderdate]) AS ayear, DatePart("m",[orderdate])
AS amonth, Sum(Orders.Frei ght) AS SumOfFreight,
Format(DSum("Fr eight","Orders" ,"CompareDat es([orderdate], DateSerial("
& [ayear] & "," & [amonth] & " + 1, 0)) < 0" & ""),"$0,000.00" ) AS
RunTot, Format([orderdate],"mmm") AS fdate
FROM Orders
GROUP BY Orders.OrderDat e, Format([orderdate],"mmm"),
DatePart("yyyy" ,[orderdate]), DatePart("m",[orderdate])
ORDER BY DatePart("yyyy" ,[orderdate]), DatePart("m",[orderdate]),
Format([orderdate],"mmm");
returns a different RunTot:
RunTot
$0,025.00
$0,040.50
$0,062.50
$0,095.94
$0,317.94
$0,650.94
$1,094.94
$1,098.54
A DSum in a query is not much different than a query inside a query.
James A. Fortune
John Winterbottom wrote: select format$(m.month Start,"mmm-yyyy") as month, ( select sum(o2.Freight) from orders as o2 where o2.OrderDate >= m.monthStart and o2.OrderDate < m.monthEnd ) as SumOfFreight, ( select sum(o2.Freight) from orders as o2 where o2.OrderDate < m.monthEnd ) as RunTot from months as m order by m.monthStart
If you need any kind of speed at all use John's approach. I posted
another way to get the table of months a while back but it used a query
that needed a further make table query to obtain the kind of speed he's
talking about.
James A. Fortune
Jim,
That worked great for the northwinds database, when i try to get it to
work for my database I get an error.
My sql is:
SELECT DatePart("yyyy" ,[minofdate]) AS ayear, DatePart("m",[minofdate])
AS amonth,
Sum(graphev.50% compev) AS sumof50%compev,
Format(DSum("[50%compev]","graphev","Co mpareDates([minofdate],
DateSerial("& [ayear] & "," & [amonth] & " + 1, 0)) < 0" &
""),"$0,000.00" ) AS RunTot, Format([minofdate],"mmm") AS fdate
FROM graphev;
I get an error that says: Syntax error in query expression
'Sum(graphev.50 %compev)'
> I get an error that says: Syntax error in query expression 'Sum(graphev.50 %compev)'
Since your field name includes a non-alphabetic character (the percent
sign), you always have to enclose it in square brackets. In general,
however, it's not a terribly good idea to use symbols in a field name.
(Well, I guess underscores and hyphens are ok.)
--
HTH,
Martha
(don't google to email)
I changed my query to take out the % sign. Here is my new query:
SELECT DatePart("yyyy" ,[minofdate]) AS ayear, DatePart("m",[minofdate])
AS amonth, sum(evgraph.50c ompev) AS sumof50compev,
Format(DSum("50 compev","graphe v","CompareDate s([minofdate],
DateSerial("& [ayear] & "," & [amonth] & " + 1, 0)) < 0" &
""),"$0,000.00" ) AS RunTot, Format([minofdate],"mmm") AS fdate
FROM graphev;
Now I get "Syntax error (missing operator) in query expression
'sum(evgraph.50 compev)'.
If i bracket [50compev] i get "you tried to execute a query that does
not include the specified expression 'datepart("yyyy ,[minofdate])' as
part of an aggregate function.
turtle wrote: I changed my query to take out the % sign. Here is my new query:
SELECT DatePart("yyyy" ,[minofdate]) AS ayear,
DatePart("m",[minofdate]) AS amonth, sum(evgraph.50c ompev) AS sumof50compev, Format(DSum("50 compev","graphe v","CompareDate s([minofdate], DateSerial("& [ayear] & "," & [amonth] & " + 1, 0)) < 0" & ""),"$0,000.00" ) AS RunTot, Format([minofdate],"mmm") AS fdate FROM graphev;
Now I get "Syntax error (missing operator) in query expression 'sum(evgraph.50 compev)'. If i bracket [50compev] i get "you tried to execute a query that does not include the specified expression 'datepart("yyyy ,[minofdate])' as part of an aggregate function.
You can change CompareDates to:
Public Function CompareDates(dt 1 As Date, dt2 As Date) As Integer
If dt1 < dt2 Then
CompareDates = -1
ElseIf dt1 > dt2 Then
CompareDates = 1
Else
CompareDates = 0
End If
End Function
Or just use "[orderdate] < DateSerial("& [ayear] & "," & [amonth] & " +
1, 0)" instead of CompareDates(([orderdate], DateSerial("
& [ayear] & "," & [amonth] & " + 1, 0)) < 0"
The query I used to get a list of months is in: http://groups-beta.google.com/group/...31790ec0622af9
Convert qryDisplayMonth s to a Make Table query if performance is an
issue. Still, take a good look at what John wrote. It's pretty nice.
I haven't looked at the latest problem yet.
James A. Fortune
turtle wrote: I changed my query to take out the % sign. Here is my new query:
SELECT DatePart("yyyy" ,[minofdate]) AS ayear,
DatePart("m",[minofdate]) AS amonth, sum(evgraph.50c ompev) AS sumof50compev, Format(DSum("50 compev","graphe v","CompareDate s([minofdate], DateSerial("& [ayear] & "," & [amonth] & " + 1, 0)) < 0" & ""),"$0,000.00" ) AS RunTot, Format([minofdate],"mmm") AS fdate FROM graphev;
Now I get "Syntax error (missing operator) in query expression 'sum(evgraph.50 compev)'. If i bracket [50compev] i get "you tried to execute a query that does not include the specified expression 'datepart("yyyy ,[minofdate])' as part of an aggregate function.
The 50compev is summed over the month of those minofdate's. If that's
what you want then you need to isolate each month with the group by.
Month alone isn't enough so the year of minofdate had to be included as
well. Perhaps explain what you are really trying to do. Also, the SQL
might be a lot simpler given that explanation.
James A. Fortune
Jim,
I think your last solution helped me!!! thanks.
Basically I am creating an Earned Value database so I need to know the
earned value for each month per Job. In the month the job starts the
earned value becomes 50% of the budget. When the job is completed the
Earned Value gets the other 50% of the budget. I want to create a
graph (hence the running sum) to show Earned Value. I think it is
working right now. Now I need to do the same thing with Budget and
Actuals and show all on one graph. I do believe that I will need to
make the months table and go from there.
thanks for your help!
Keith This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Sgt. Sausage |
last post by:
I've got a server (SQL 2K, Win2K) where the backups
have started running long.
The database is a bit largish -- 150GB or so. Up until
last month, the backups were taking on the order of
4 to 5 hours -- depending on the level of activity on the
server.
I'm using a T-SQL script in the SQLAgent to run the
backups. Native SQL backup to an AIT tape drive.
|
by: Richard Hollenbeck |
last post by:
I'm trying to write some code that will convert any of the most popular
standard date formats twice in to something like "dd Mmm yyyy" (i.e. 08 Jan
1908) and compare the first with the second and calculate days, months, and
years. This is not for a college course. It's for my own personal
genealogy website. I'm stumped about the code. I'm working on it but not
making much progress. Is there any free code available anywhere? I know it...
|
by: KashMarsh |
last post by:
Trying to show running totals on a report, except it needs to show one
total amount and values being subtracted from it. For example,
the report shows a Total Inventory amount (TotInvAmt). And then
amounts for each month for the orders like JanAmt, FebAmt, etc. I want
to show under each month column the following:
(TotInvAmt)-(JanAmt)=B ----result shows under the Jan column
B-(FebAmt)=C ---------result shows under the Feb column...
|
by: Gorlon the Impossible |
last post by:
Hello
I'm not sure how to phrase this question. I have a Python function
that sends MIDI messages to a synth. When I run it, I of course have
to wait until it is finished before I can do anything else with
Python. Is it possible to run this function and still be able to do
other things with Python while it is running? Is that what threading
is about?
|
by: Michel |
last post by:
Hi, I wrote an app in .Net and I whant only 1 instance of this app open for
the user; the user open my app, do some works and try to open another
instance of my app, I whant to show a message to user to inform him that only
one instance is permit and then close the second instance after that.
I am able to do this when the user run the application on his PC whit this :
Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName)
...
| |
by: Mark |
last post by:
why doesn't .NET support multiple inheritance?
I think it's so silly!
Cheers,
Mark
|
by: Vikas |
last post by:
Hi all,
I am working on a document control database where I have a table
"tblControl" containing two columns "DocID" and "SchIssueDate".
"DocID" is the key field with text format while "SchIssueDate" is Date
format.
I am trying to create a S-Curve for the documents to be issued each
month to show the required progress. I have made this query for this:
SELECT Format(,"mmm-yyyy") AS ,
|
by: mathieu |
last post by:
I'd like to be able to get the path to the current working executable
(from inside it).
Technically this is easy, I simply have to collapse: getcwd and
argv
Well argv comes in a little late, I'd like to have access to this
information before the 'main' function is called. Is there a way to
get the path to an executable (from inside it) ?
|
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,...
|
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...
|
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...
| |
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,...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |