基于另一个字段中的日期范围在一个字段中求和值

时间:2015-04-15 09:49:22

标签: ms-access calculated-field

我有两张桌子,都有日期(这是他们将要加入的内容)

Table 1每日降雨量值

Table 2每周有一个水量值。

我试图让Access根据水量的日期计算每周降雨量(从每日数值),即:动态计算的两个日期之间的总降雨量。我有使用Access SQL的一些经验,但我对此感到困惑。为了增加并发症,每隔一段时间,音量值不会相隔7天。

1 个答案:

答案 0 :(得分:1)

一种方法是从每个表中查找周数,然后在这些表之间加入:

Select 
    Sum(Table1.Volume) As Volume1, 
    ISO_Weeknumber(Table1.[datefield]) As WeekNumber1, 
    Sum(Table2.Volume) As Volume2, 
    ISO_Weeknumber(Table2.[datefield]) As WeekNumber2 
From 
    Table1
Inner Join
    Table2
    On ISO_Weeknumber(Table1.[datefield])=ISO_Weeknumber(Table2.[datefield])
Group By 
    ISO_Weeknumber(Table1.[datefield]),
    ISO_Weeknumber(Table2.[datefield])

使用此功能:

Public Function ISO_WeekYearNumber( _
  ByVal datDate As Date, _
  Optional ByRef intYear As Integer, _
  Optional ByRef bytWeek As Byte) _
  As String

' Calculates and returns year and week number for date datDate according to the ISO 8601:1988 standard.
' Optionally returns numeric year and week.
' 1998-2007, Gustav Brock, Cactus Data ApS, CPH.
' May be freely used and distributed.

  Const cbytFirstWeekOfAnyYear  As Byte = 1
  Const cbytLastWeekOfLeapYear  As Byte = 53
  Const cbytMonthJanuary        As Byte = 1
  Const cbytMonthDecember       As Byte = 12
  Const cstrSeparatorYearWeek   As String = "W"

  Dim bytMonth                  As Byte
  Dim bytISOThursday            As Byte
  Dim datLastDayOfYear          As Date

  intYear = Year(datDate)
  bytMonth = Month(datDate)
  bytWeek = DatePart("ww", datDate, vbMonday, vbFirstFourDays)

  If bytWeek = cbytLastWeekOfLeapYear Then
    bytISOThursday = Weekday(vbThursday, vbMonday)
    datLastDayOfYear = DateSerial(intYear, cbytMonthDecember, 31)
    If Weekday(datLastDayOfYear, vbMonday) >= bytISOThursday Then
      ' OK, week count of 53 is caused by leap year.
    Else
      ' Correct for Access97/2000+ bug.
      bytWeek = cbytFirstWeekOfAnyYear
    End If
  End If

  ' Adjust year where week number belongs to next or previous year.
  If bytMonth = cbytMonthJanuary Then
    If bytWeek >= cbytLastWeekOfLeapYear - 1 Then
      ' This is an early date of January belonging to the last week of the previous year.
      intYear = intYear - 1
    End If
  ElseIf bytMonth = cbytMonthDecember Then
    If bytWeek = cbytFirstWeekOfAnyYear Then
      ' This is a late date of December belonging to the first week of the next year.
      intYear = intYear + 1
    End If
  End If

  ISO_WeekYearNumber = CStr(intYear) & cstrSeparatorYearWeek & Format(bytWeek, "00")

End Function

为此,您必须在表1中存在表2中的所有周,反之亦然。