2016-02-11 49 views
0

我已經搜索過,但所有結果都沒有幫助我理解。MS Access在兩個日期之間選擇?

我需要選擇18-23歲的人的姓名。 所以我的嘗試是:

WHERE ((People.Birth) Between (Now()-Year(18)) And (Now()-Year(23))) 

我做錯了什麼?解決方案#some_date#是一個壞主意!

+1

你是否調查過「Year(18)'實際返回的結果? –

+0

請參閱[datediff](https://support.office.com/zh-cn/article/DateDiff-Function-e6dd7ee6-3d01-4531-905c-e24fc238f85f)。 – user2864740

+0

f * ck,很多時候都明白,所有問題都需要在睡眠後解決,而不是在25小時後解決。年份(18)將返回1900 ... 2 user2864740 - 我已經看到它,但它對我沒有幫助( –

回答

1

對於一個真正的解決方案,你需要使用使用DateAdd和這樣的功能:

Public Function AgeSimple(_ 
    ByVal datDateOfBirth As Date) _ 
    As Integer 

' Returns the difference in full years from datDateOfBirth to current date. 
' 
' Calculates correctly for: 
' leap years 
' dates of 29. February 
' date/time values with embedded time values 
' 
' DateAdd() is used for check for month end of February as it correctly 
' returns Feb. 28. when adding a count of years to dates of Feb. 29. 
' when the resulting year is a common year. 
' After an idea of Markus G. Fischer. 
' 
' 2007-06-26. Cactus Data ApS, CPH. 

    Dim datToday As Date 
    Dim intAge As Integer 
    Dim intYears As Integer 

    datToday = Date 
    ' Find difference in calendar years. 
    intYears = DateDiff("yyyy", datDateOfBirth, datToday) 
    If intYears > 0 Then 
    ' Decrease by 1 if current date is earlier than birthday of current year 
    ' using DateDiff to ignore a time portion of datDateOfBirth. 
    intAge = intYears - Abs(DateDiff("d", datToday, DateAdd("yyyy", intYears, datDateOfBirth)) > 0) 
    End If 

    AgeSimple = intAge 

End Function 

然後你的查詢就會有這個其中子句:

WHERE AgeSimple(People.Birth) Between 18 And 23 
+0

哇。 –

0

最後解決它通過簡單的

WHERE ((People.Birth) Between (Now()- 365*18) And (Now()-365*23)) 

如果你有更好的解決方案 - 歡迎

+0

太簡單了, – Gustav

相關問題