我正在Access中使用SQL,这是我以前从未做过的,在此工作中我没有其他SQL选项。
我有Table1.Service_Date
和Table2.Service_Date
我正在尝试创建一个包含Table2.Service_Date
的where语句,如果该语句出现在Table1.Service_date
前六个月或更短的时间。
答案 0 :(得分:1)
您可以做的是内部联接语句,以链接适合您范围的数据。
SELECT *
FROM Table1 t1
INNER JOIN on Table2 t2 ON ((DATEADD(t1.Service_Date, -6, MONTH) <= t2.Service_Date)
AND (t1.Service_Date >= t2.Service_Date))
-- any WHERE statement to filter the dates
;
您可能对<=
或>=
条件有不同的需求,因此请根据您的需求调整解决方案。
答案 1 :(得分:1)
它将是:
Where Table2.Service_Date <= DateAdd("m", -6, Table1.Service_Date)
或:
Where DateAdd("m", 6, Table2.Service_Date) <= Table1.Service_Date
选择哪种方式取决于如何处理ultimo的日期 -28、29、30和31。
如果都不适合,请使用此功能:
Public Function DateAddMonth( _
ByVal datDate As Date, _
Optional ByVal intIncrement As Integer = 1, _
Optional ByVal booLeapYearIgnore As Boolean = True) _
As Date
' Add intIncrement number of months to datDate.
' If datDate is ultimo, return date will also be ultimo.
'
' 1999-10-21, Gustav Brock, Cactus Data ApS, Copenhagen
Dim datDateNext As Date
Dim booUltimo As Boolean
' No specific error handling.
On Error Resume Next
' Add one day.
datDateNext = DateAdd("d", 1, datDate)
' If datDate is ultimo, next day will be the first of the next month.
booUltimo = (Day(datDateNext) = 1)
If (Not booUltimo) And booLeapYearIgnore Then
' Regard February 28 as ultimo also for leap years.
If (Month(datDate) = 2) And (Day(datDate) = 28) Then
' Add one more day.
datDateNext = DateAdd("d", 1, datDateNext)
booUltimo = True
End If
End If
If booUltimo Then
' Add intIncrement number of months to the first of next month.
datDateNext = DateAdd("m", intIncrement, datDateNext)
' Decrement one day.
' As datDate is ultimo, the month will be decremented too.
datDateNext = DateAdd("d", -1, datDateNext)
Else
' Add intIncrement number of months to datDate.
datDateNext = DateAdd("m", intIncrement, datDate)
End If
DateAddMonth = datDateNext
End Function
以及以下任意一项:
Where Table2.Service_Date <= DateAddMonth(Table1.Service_Date, -6)
Where DateAddMonth(Table2.Service_Date, 6) <= Table1.Service_Date