Рассчитать полные месяцы между двумя датами в MS ACCESS Query - PullRequest
0 голосов
/ 25 октября 2018

У меня проблема с использованием функции ACCESS DateDiff.Я пытаюсь получить полные месяцы между двумя датами, однако эта функция игнорирует даты в середине месяца.По-видимому, он выполняет простой расчет самого номера месяца и не учитывает день месяца.

Например : если я хочу узнать полный месяц между 16 октября и 3 ноября.Это должно вернуть ноль, однако функция DateDiff возвращает 1. Какой код мне нужно реализовать, чтобы получить полные месяцы между и заставить его работать ВСЕ МЕСЯЦЫ.Я говорю, что ВСЕ месяцы как месяцы могут иметь 28 дней (29 в високосном году), 30 дней и 31 день, поэтому я не буду просто вычислять дни между двумя датами.

Access Function:DateDiff ("m", PAID_DATE, STATIC_DATE) AS Months_Between

На снимке экрана ниже показаны нужные данные, а также неверный месяц между полученными результатами.

enter image description here

И, наконец, снимок экрана простого представления моих выходных данных в представлении ACCESS Design.

enter image description here

Oracle Пример того, что я пытаюсь выполнить в ACCESS

Я могу сделать это в Oracle очень просто, поскольку функция Months_Between оракула учитывает месяцы, високосные годы и днив течение каждого месяца и выводит фактические месяцы между значениями.Если бы я знал, как получить это в ACCESS, я бы не стал публиковать этот вопрос.

enter image description here

1 Ответ

0 голосов
/ 25 октября 2018

Вам понадобится пользовательская функция, подобная этой:

Public Function Months( _
  ByVal datDate1 As Date, _
  ByVal datDate2 As Date, _
  Optional ByVal booLinear As Boolean) _
  As Integer

' Returns the difference in full months between datDate1 and datDate2.
'
' Calculates correctly for:
'   negative differences
'   leap years
'   dates of 29. February
'   date/time values with embedded time values
'   negative date/time values (prior to 1899-12-29)
'
' Optionally returns negative counts rounded down to provide a
' linear sequence of month counts.
' For a given datDate1, if datDate2 is decreased stepwise one month from
' returning a positive count to returning a negative count, one or two
' occurrences of count zero will be returned.
' If booLinear is False, the sequence will be:
'   3, 2, 1, 0,  0, -1, -2
' If booLinear is True, the sequence will be:
'   3, 2, 1, 0, -1, -2, -3
'
' If booLinear is False, reversing datDate1 and datDate2 will return
' results of same absolute Value, only the sign will change.
' This behaviour mimics that of Fix().
' If booLinear is True, reversing datDate1 and datDate2 will return
' results where the negative count is offset by -1.
' This behaviour mimics that of Int().

' DateAdd() is used for check for month end of February as it correctly
' returns Feb. 28. when adding a count of months to dates of Feb. 29.
' when the resulting year is a common year.
'
' 2010-03-30. Cactus Data ApS, CPH.

  Dim intDiff   As Integer
  Dim intSign   As Integer
  Dim intMonths As Integer

  ' Find difference in calendar months.
  intMonths = DateDiff("m", datDate1, datDate2)
  ' For positive resp. negative intervals, check if the second date
  ' falls before, on, or after the crossing date for a 1 month period
  ' while at the same time correcting for February 29. of leap years.
  If DateDiff("d", datDate1, datDate2) > 0 Then
    intSign = Sgn(DateDiff("d", DateAdd("m", intMonths, datDate1), datDate2))
    intDiff = Abs(intSign < 0)
  Else
    intSign = Sgn(DateDiff("d", DateAdd("m", -intMonths, datDate2), datDate1))
    If intSign <> 0 Then
      ' Offset negative count of months to continuous sequence if requested.
      intDiff = Abs(booLinear)
    End If
    intDiff = intDiff - Abs(intSign < 0)
  End If

  ' Return count of months as count of full 1 month periods.
  Months = intMonths - intDiff

End Function
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...