473,498 Members | 2,018 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Filtering query by dates

296 Recognized Expert Contributor
I have a lengthy query that I am now trying to filter. The query calculates an employee's Anniversary Date in which they are eligible for the next level of Annual Vacation. (i.e. For 1-6 years of service, you qualify for 15 days vacation, etc.) I am trying to filter the report to show only those names whose anniversary date falls into the following year. Employees are entitled to their vacation Jan.1 of their upcoming anniversary date. (i.e., if an individual's anniversary date is March 26, 2008, they are entitled to their vacation Jan.1, 2008) My query currently shows all anniversary dates, which include dates such as May 11, 2011, etc. As I said, I want to filter it to show only those individuals whose anniversary date falls within the next year. So for this year, I want it to show all Anniversary Dates <= 12/31/2008. I can filter the report just fine if I actually use the date, but I want this report to be used in the future as well, so next year, it should be calculating Anniversary Dates <= 12/31/2009. It would be ideal if I could make it so that the user could input which year they would like to view. So for this year, if someone wanted to look at those eligibilities for 2009, they could. So what I'm looking for is something like this:
AnniversaryDate<=12/31/[Enter the Year]
where the user inputs the year. Not sure if this is possible. Here's my current sql minus some fields in the SELECT statement that are irrelevant and minus the FROM just to shorten the code here:
Expand|Select|Wrap|Line Numbers
  1. SELECT Employee.ServiceDate, DateDiff("d",[ServiceDate],Now()) AS TotalServiceDays, Fix(DateDiff("d",[ServiceDate],Now())/365) AS ServiceYears, Fix((((DateDiff("d",[ServiceDate],Now())/365)-[ServiceYears])*12)) AS ServiceMonths, Round((((((DateDiff("d",[ServiceDate],Now())/365)-[ServiceYears])*12)) -[ServiceMonths])*30.4583) AS ServiceDays, IIf([AnniversaryDate]<>"NA",DateSerial(Year(AnniversaryDate),1,1),"NA") AS SupplementalEligibility, Switch(DateAdd("m",60,[ServiceDate])>Now(),DateAdd("m",60,[ServiceDate]), DateAdd("m",120,[ServiceDate])>Now(),DateAdd("m",120,[ServiceDate]), DateAdd("m",180,[ServiceDate])>Now(),DateAdd("m",180,[ServiceDate]), DateAdd("m",240,[ServiceDate])>Now(),DateAdd("m",240,[ServiceDate]), DateAdd("m",300,[ServiceDate])>Now(),DateAdd("m",300,[ServiceDate]), DateAdd("m",360,[ServiceDate])>Now(),DateAdd("m",360,[ServiceDate]), DateAdd("m",420,[ServiceDate])>Now(),DateAdd("m",420,[ServiceDate]), DateAdd("m",480,[ServiceDate])>Now(),DateAdd("m",480,[ServiceDate]),True,"NA") AS AnniversaryDate, Category.Code, CategoryReason.Desc, IIf([HireDate]<>[ServiceDate],"Flag","") AS Flag
  2. FROM ......
  3. WHERE (((EmplStatus.StatusCode)="A" Or (EmplStatus.StatusCode)="LOA") AND ((CategoryReason.Desc)="Permanent") AND ((EmplCategory.Active)=True) AND ((EmplJob.Active)=True) AND ((EmplOrganization.Active)=True) AND ((EmplStatus.Active)=True));
Any help would be appreciated!
I should mention that I have tried using the DatePart function which gives me just the year, but when I try to filter it with <=2008 or <=[Enter a Year] it says it's a data type mismatch.
Sep 18 '07 #1
18 2493
Scott Price
1,384 Recognized Expert Top Contributor
Have you thought of a text box to enter the year, then concatenating the entered year with a date part function that gives today's day and month?

For example, a where criteria in your date field something like this:
Expand|Select|Wrap|Line Numbers
  1. WHERE [TableName].[DateFieldName] = DatePart("mm/dd", "July 30") & "/" & Forms![FormName]![TextBoxName]
This is just off the top of my head tonight, but I'll give it a test in the morning to see if there are any wrinkles that need ironing :-)

Regards,
Scott
Sep 19 '07 #2
mlcampeau
296 Recognized Expert Contributor
Have you thought of a text box to enter the year, then concatenating the entered year with a date part function that gives today's day and month?

For example, a where criteria in your date field something like this:
Expand|Select|Wrap|Line Numbers
  1. WHERE [TableName].[DateFieldName] = DatePart("mm/dd", "July 30") & "/" & Forms![FormName]![TextBoxName]
This is just off the top of my head tonight, but I'll give it a test in the morning to see if there are any wrinkles that need ironing :-)

Regards,
Scott
I haven't done that because I'm not using a form. This database was already created and I am having to do some tweaking to it. I shouldn't say I'm not using a form at all...there is a navigation bar that shows a list of the report names, and the user just double clicks the name to open the report. There is no room for adding textboxes and I really don't want to mess around with that navigation bar as its main function isn't to view the list of reports, but to navigate through the database. I'm really hoping that I can somehow do this in the query itself, or in VBA in the On Open event (My knowledge is very limited in VBA though).
Sep 19 '07 #3
Scott Price
1,384 Recognized Expert Top Contributor
I haven't done that because I'm not using a form. This database was already created and I am having to do some tweaking to it. I shouldn't say I'm not using a form at all...there is a navigation bar that shows a list of the report names, and the user just double clicks the name to open the report. There is no room for adding textboxes and I really don't want to mess around with that navigation bar as its main function isn't to view the list of reports, but to navigate through the database. I'm really hoping that I can somehow do this in the query itself, or in VBA in the On Open event (My knowledge is very limited in VBA though).
Well, in my test db, I created a parameter called [Please Enter Year] with type as integer and placed it in the Criteria grid of a new field. In the Field grid I put this: VacationYear: Year([YourDateField]).

Now when I run the query it pops up the parameter box, and then filters the query results according to the year I enter.

Is this something like you're looking for?

Regards,
Scott
Sep 19 '07 #4
mlcampeau
296 Recognized Expert Contributor
Well, in my test db, I created a parameter called [Please Enter Year] with type as integer and placed it in the Criteria grid of a new field. In the Field grid I put this: VacationYear: Year([YourDateField]).

Now when I run the query it pops up the parameter box, and then filters the query results according to the year I enter.

Is this something like you're looking for?

Regards,
Scott
That's exactly what I'm looking for, Scott, except it doesn't work. My date field is [AnniversaryDate], which is an expression in the same query. The Year([AnniversaryDate]) works great - it gives me the correct year, but as soon as I try to add criteria, (<=[Please Enter Year]), it also asks me for the value of AnniversaryDate.
If I try replacing [AnniversaryDate] with the expression, it works until I try to add criteria - then it says the expression is typed incorrectly, or it is too complex to be evaluated.
Expand|Select|Wrap|Line Numbers
  1. Year((Switch(DateAdd("m",60,[ServiceDate])>Now(),DateAdd("m",60,[ServiceDate]),DateAdd("m",120,[ServiceDate])>Now(),DateAdd("m",120,[ServiceDate]),DateAdd("m",180,[ServiceDate])>Now(),DateAdd("m",180,[ServiceDate]),DateAdd("m",240,[ServiceDate])>Now(),DateAdd("m",240,[ServiceDate]),DateAdd("m",300,[ServiceDate])>Now(),DateAdd("m",300,[ServiceDate]),DateAdd("m",360,[ServiceDate])>Now(),DateAdd("m",360,[ServiceDate]),DateAdd("m",420,[ServiceDate])>Now(),DateAdd("m",420,[ServiceDate]),DateAdd("m",480,[ServiceDate])>Now(),DateAdd("m",480,[ServiceDate]),True,"NA"))) AS VacationYear
I haven't made the parameter an integer because I'm not really sure how to do that...would that make a difference?
Sep 19 '07 #5
mlcampeau
296 Recognized Expert Contributor
I haven't made the parameter an integer because I'm not really sure how to do that...would that make a difference?
Okay, I searched how to declare the parameter as an integer and it hasn't helped at all....
Sep 19 '07 #6
Scott Price
1,384 Recognized Expert Top Contributor
WHERE (((Year([OrderEventDate]))<=[Please Enter Year]));

This is exactly the way I have it in my query that is working...

The Parameter [Please Enter Year] probably doesn't have to be declared as an Integer...

Regards,
Scott
Sep 19 '07 #7
mlcampeau
296 Recognized Expert Contributor
WHERE (((Year([OrderEventDate]))<=[Please Enter Year]));

This is exactly the way I have it in my query that is working...

The Parameter [Please Enter Year] probably doesn't have to be declared as an Integer...

Regards,
Scott
Scott,
Your logic does work. I tested it on my ServiceDate field that is stored in a table. The problem is that I'm trying to filter this based on a date that I am calculating. I am trying to use:
WHERE (((Year([AnniversaryDate]))<=[Please Enter Year]))
but since Anniversary Date is actually this:
Expand|Select|Wrap|Line Numbers
  1. Switch(DateAdd("m",60,[ServiceDate])>Now(),DateAdd("m",60,[ServiceDate]),DateAdd("m",120,[ServiceDate])>Now(),DateAdd("m",120,[ServiceDate]),DateAdd("m",180,[ServiceDate])>Now(),DateAdd("m",180,[ServiceDate]),DateAdd("m",240,[ServiceDate])>Now(),DateAdd("m",240,[ServiceDate]),DateAdd("m",300,[ServiceDate])>Now(),DateAdd("m",300,[ServiceDate]),DateAdd("m",360,[ServiceDate])>Now(),DateAdd("m",360,[ServiceDate]),DateAdd("m",420,[ServiceDate])>Now(),DateAdd("m",420,[ServiceDate]),DateAdd("m",480,[ServiceDate])>Now(),DateAdd("m",480,[ServiceDate]),True,"NA")
I'm having troubles. I think I mentioned before that if I put Year([AnniversaryDate]), it gives me the correct year, it's just when I try to add the filter that the problems arise. Any ideas??
Sep 19 '07 #8
FishVal
2,653 Recognized Expert Specialist
Hi, mlcampeau.

Not sure whether this will help.
Try to build a second query to filter the records returned by your query.

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM [YourQuery] WHERE [AnniversaryDate] < [Please Enter Year];
  2.  
If this doesn't help, then try to put "Switch logic" to a public VBA function and use it in your query instead of Year(Switch(...)) expression

Expand|Select|Wrap|Line Numbers
  1. Public Function GetAnniversaryYear(ByVal dteServiceDate As Date) As Variant
  2.  
  3.     Dim i As Integer
  4.  
  5.     For i = 60 To 480 Step 60
  6.         If DateAdd("m", i, dteServiceDate) > Date Then
  7.             GetAnniversaryYear = Year(DateAdd("m", i, dteServiceDate))
  8.             Exit Function
  9.         End If
  10.     Next i
  11.  
  12.     GetAnniversaryYear = Null
  13.  
  14. End Function
  15.  
  16.  
Sep 19 '07 #9
mlcampeau
296 Recognized Expert Contributor
Hi, mlcampeau.

Not sure whether this will help.
Try to build a second query to filter the records returned by your query.

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM [YourQuery] WHERE [AnniversaryDate] < [Please Enter Year];
  2.  
If this doesn't help, then try to put "Switch logic" to a public VBA function and use it in your query instead of Year(Switch(...)) expression

Expand|Select|Wrap|Line Numbers
  1. Public Function GetAnniversaryYear(ByVal dteServiceDate As Date) As Variant
  2.  
  3.     Dim i As Integer
  4.  
  5.     For i = 60 To 480 Step 60
  6.         If DateAdd("m", i, dteServiceDate) > Date Then
  7.             GetAnniversaryYear = Year(DateAdd("m", i, dteServiceDate))
  8.             Exit Function
  9.         End If
  10.     Next i
  11.  
  12.     GetAnniversaryYear = Null
  13.  
  14. End Function
  15.  
  16.  
I've tried creating the second query. Seems like it should work, but it doesn't. One thing I'm noticing is that if I sort the results by AnniversaryDate, it doesn't sort it by date, but rather, by the digits. For example it sorts like this:
1/1/2009
1/10/2009
1/11/2009
1/13/2012
1/15/2010
1/15/2012
1/18/2008
1/2/2011
1/22/2008
1/23/2010
etc....
I assume it's due to the format of the field. I'm not sure how to declare the format in a query, except for in the design view, right click on the grid, choose properties. But for the AnniversaryDate field, when I click the drop down box under Format, there are no options. I tried just typing in Short Date, but that doesn't do anything. Anyway, I'm not sure if that would have anything to do with why I'm having problems filtering this.

As for trying to add the public function, I'm really new to VBA...how would I refer to that function in my query?
Sep 19 '07 #10
FishVal
2,653 Recognized Expert Specialist
  • Open VBA window.
  • Main Menu > Insert > Module.
  • Paste the code.
  • Save the module.
  • Use the function in your query as a regular VBA function you use
    e.g.
    Expand|Select|Wrap|Line Numbers
    1. SELECT ......, GetAnniversaryYear([ServiceDate]) AS AnniversaryYear FROM ...
    2.  

The function returns anniversary year.
If you want to get anniversary date, then use this slightly modified code.
Expand|Select|Wrap|Line Numbers
  1. Public Function GetAnniversaryDate(ByVal dteServiceDate As Date) As Variant
  2.  
  3.     Dim i As Integer
  4.  
  5.     For i = 60 To 480 Step 60
  6.         If DateAdd("m", i, dteServiceDate) > Date Then
  7.             GetAnniversaryDate = DateAdd("m", i, dteServiceDate)
  8.             Exit Function
  9.         End If
  10.     Next i
  11.  
  12.     GetAnniversaryDate = Null
  13.  
  14. End Function
  15.  
Sep 19 '07 #11
mlcampeau
296 Recognized Expert Contributor
  • Open VBA window.
  • Main Menu > Insert > Module.
  • Paste the code.
  • Save the module.
  • Use the function in your query as a regular VBA function you use
    e.g.
    Expand|Select|Wrap|Line Numbers
    1. SELECT ......, GetAnniversaryYear([ServiceDate]) AS AnniversaryYear FROM ...
    2.  

The function returns anniversary year.
If you want to get anniversary date, then use this slightly modified code.
Expand|Select|Wrap|Line Numbers
  1. Public Function GetAnniversaryDate(ByVal dteServiceDate As Date) As Variant
  2.  
  3.     Dim i As Integer
  4.  
  5.     For i = 60 To 480 Step 60
  6.         If DateAdd("m", i, dteServiceDate) > Date Then
  7.             GetAnniversaryDate = DateAdd("m", i, dteServiceDate)
  8.             Exit Function
  9.         End If
  10.     Next i
  11.  
  12.     GetAnniversaryDate = Null
  13.  
  14. End Function
  15.  
I created the module and saved it as GetAnniversaryYear (I'm using the code that just gives the year). When I tried adding
SELECT ......, GetAnniversaryYear([ServiceDate]) AS AnniversaryYear
I get an error saying that GetAnniversaryYear is an undefined function... Any thoughts?
Sep 19 '07 #12
mlcampeau
296 Recognized Expert Contributor
Putting this:
Expand|Select|Wrap|Line Numbers
  1. WHERE ....(((Switch(DateAdd("m",60,[ServiceDate])>Now(),DateAdd("m",60,[ServiceDate]),DateAdd("m",120,[ServiceDate])>Now(),DateAdd("m",120,[ServiceDate]),DateAdd("m",180,[ServiceDate])>Now(),DateAdd("m",180,[ServiceDate]),DateAdd("m",240,[ServiceDate])>Now(),DateAdd("m",240,[ServiceDate]),DateAdd("m",300,[ServiceDate])>Now(),DateAdd("m",300,[ServiceDate]),DateAdd("m",360,[ServiceDate])>Now(),DateAdd("m",360,[ServiceDate]),DateAdd("m",420,[ServiceDate])>Now(),DateAdd("m",420,[ServiceDate]),DateAdd("m",480,[ServiceDate])>Now(),DateAdd("m",480,[ServiceDate]),True,"NA")))<="12/31" & "/" & [Enter the Year]))
filters it, but not the way I want. As I mentioned in a previous post, Access is not reading this field as a Date. So by me saying <="12/31" & "/" & [Enter the Year], and then I type 2008 in the prompt, it is giving me all results where the month starts with a 1 (i.e. 1/1/2008, 10/20/2010, 11/13/2009, 12/30/2011, etc...) So is filtering by month, day, then year. Somehow I need Access to realize that it is a date field so that it sorts properly. If I can get that to happen, the above criteria would work....
Sep 19 '07 #13
Scott Price
1,384 Recognized Expert Top Contributor
Putting this:
Expand|Select|Wrap|Line Numbers
  1. WHERE ....(((Switch(DateAdd("m",60,[ServiceDate])>Now(),DateAdd("m",60,[ServiceDate]),DateAdd("m",120,[ServiceDate])>Now(),DateAdd("m",120,[ServiceDate]),DateAdd("m",180,[ServiceDate])>Now(),DateAdd("m",180,[ServiceDate]),DateAdd("m",240,[ServiceDate])>Now(),DateAdd("m",240,[ServiceDate]),DateAdd("m",300,[ServiceDate])>Now(),DateAdd("m",300,[ServiceDate]),DateAdd("m",360,[ServiceDate])>Now(),DateAdd("m",360,[ServiceDate]),DateAdd("m",420,[ServiceDate])>Now(),DateAdd("m",420,[ServiceDate]),DateAdd("m",480,[ServiceDate])>Now(),DateAdd("m",480,[ServiceDate]),True,"NA")))<="12/31" & "/" & [Enter the Year]))
filters it, but not the way I want. As I mentioned in a previous post, Access is not reading this field as a Date. So by me saying <="12/31" & "/" & [Enter the Year], and then I type 2008 in the prompt, it is giving me all results where the month starts with a 1 (i.e. 1/1/2008, 10/20/2010, 11/13/2009, 12/30/2011, etc...) So is filtering by month, day, then year. Somehow I need Access to realize that it is a date field so that it sorts properly. If I can get that to happen, the above criteria would work....
What happens if you wrap the calculated date in CDate() function?

Regards,
Scott
Sep 19 '07 #14
mlcampeau
296 Recognized Expert Contributor
What happens if you wrap the calculated date in CDate() function?

Regards,
Scott
It comes up with "The expression is typed incorrectly or is too complex to evaluate." If I get rid of the criteria, it will display in the results, but if I try to sort it in the datasheet view, it says Datatype mismatch.
Sep 19 '07 #15
FishVal
2,653 Recognized Expert Specialist
No wonder it filters date as string as long as you use string criteria.
Try to change
"12/31" & "/" & [Enter the Year]
to
DateSerial([Enter the Year], 12, 31).
or
CDate("12/31" & "/" & [Enter the Year])
as Scott have suggested

Additionally:
"n/a" 's returned with Switch expression are expected cause "Type mismatch" error
Possible solutions:
1. Make Switch expression to return Null instead of "n/a"
2. VBA code where error can be trapped or prevented. Like this.
Expand|Select|Wrap|Line Numbers
  1. Public Function IsYearLessOrEqual(ByVal dteInput As Variant, _
  2.                                   ByVal lngYear As Variant) As Boolean
  3.  
  4.     IsYearLessOrEqual = False
  5.     On Error GoTo Exit_IsYearLessOrEqual
  6.     If Year(dteInput) <= lngYear Then IsYearLessOrEqual = True
  7.  
  8. Exit_IsYearLessOrEqual:
  9.  
  10. End Function
  11.  
Sep 19 '07 #16
mlcampeau
296 Recognized Expert Contributor
No wonder it filters date as string as long as you use string criteria.
Try to change
"12/31" & "/" & [Enter the Year]
to
DateSerial([Enter the Year], 12, 31).
or
CDate("12/31" & "/" & [Enter the Year])
as Scott have suggested

Additionally:
"n/a" 's returned with Switch expression are expected cause "Type mismatch" error
Possible solutions:
1. Make Switch expression to return Null instead of "n/a"
2. VBA code where error can be trapped or prevented. Like this.
Expand|Select|Wrap|Line Numbers
  1. Public Function IsYearLessOrEqual(ByVal dteInput As Variant, _
  2.                                   ByVal lngYear As Variant) As Boolean
  3.  
  4.     IsYearLessOrEqual = False
  5.     On Error GoTo Exit_IsYearLessOrEqual
  6.     If Year(dteInput) <= lngYear Then IsYearLessOrEqual = True
  7.  
  8. Exit_IsYearLessOrEqual:
  9.  
  10. End Function
  11.  
I knew it had to be something simple! I changed my criteria to:
DateSerial([Enter the Year], 12, 31) and that works great! Thanks so much, both of you, for your help!
Sep 19 '07 #17
FishVal
2,653 Recognized Expert Specialist
Happy coding.
And good luck in the rest of your project(s).

Best regards,
Fish
Sep 19 '07 #18
Scott Price
1,384 Recognized Expert Top Contributor
Glad you got it worked out!

Happy coding :-)

Regards,
Scott
Sep 19 '07 #19

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

Similar topics

6
2411
by: paii | last post by:
I have a table that stores job milestone dates. The 2 milestones I am interested in are "Ship Date" TypeID 1 and "Revised Ship Date" TypeID 18. All jobs have TypeID 1 only some jobs have TypeID 18....
1
2460
by: Ken | last post by:
I wrote a function to use in queries that takes a date and adds or subtracts a certain length time and then returns the new value. There are times when my function needs to return Null values. ...
7
14784
by: | last post by:
Hello, Does anyone have an idea on how I can filter the data in the gridview control that was returned by an sql query? I have a gridview that works fine when I populate it with data. Now I...
8
6386
by: Ragbrai | last post by:
Howdy All, I have a query that is used for filtering results to be used in a combo box. The query needs to test fields from both a table and then unbound text boxes on the form that also contains...
3
1859
by: iamguyster | last post by:
Hi, I have an exercise I need to give to my pupils (I'm a teacher!) and I am trying to get a query working preferably using the query design view, without having to edit the SQL. The query involves...
3
1361
by: panjap | last post by:
hi, i was wondering could anyone help me with a query i have created. i have sucessfully worked out the total amount od prodcuts sold in a shop. However i want a query to show the total sold of one...
4
2174
by: roryok | last post by:
Hi, (Access 2002 & Windows XP Pro) I have a Select query and one of the columns has the following criteria: (from SQL view) HAVING (((order.orderDate)>=!! And (order.orderDate)<=!!)); This...
2
1561
by: Big X | last post by:
Hi, I am having a little trouble with some data I have been sent. Seems they want me to remove all the date that have a 5 year expiry date. I receive the data in csv file so the properties of the...
3
1587
by: zandiT | last post by:
Hello I have an access report and im using a query to filter the report using Date parameters eg Start Date-12 May 2009 and End Date-30 September 2009. the query works perfectly. My problem is...
0
6993
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...
0
7197
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...
1
6881
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...
0
7375
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...
0
5456
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,...
0
4584
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...
0
3088
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3078
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
650
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.