最简单的方法 SELECT * FROM MyTable WHERE mydate 在特定周数?

Simplest way to SELECT * FROM MyTable WHERE mydate is in specific week number?

是否有一种简单的方法来 select 并对日期在特定周数中的行求和?

像这样的代码?

mysum = RS.execute("Select Sum(mypoints) as sumpoints from MyTable WHERE 
  datepart(week, mydate) = '42'")("sumpoints")

SQL 语句和 DatePart() 函数的正确语法 - 使用星期日的默认一周第一天:

SELECT Sum(mypoints) AS sumpoints FROM MyTable WHERE DatePart("ww", mydate) = 42

因为您可能将 星期一 作为一周的第一天,所以应该是:

Select Sum(mypoints) As sumpoints 
From MyTable 
Where DatePart('ww', mydate, 2) = 42

但是,如果您需要精确的 ISO 8601 周编号,则必须使用如下自定义函数:

Public Function ISO_WeekNumber( _
  ByVal datDate As Date) _
  As Byte

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

  Const cbytFirstWeekOfAnyYear  As Byte = 1
  Const cbytLastWeekOfLeapYear  As Byte = 53

  Dim bytWeek                   As Byte
  Dim bytISOThursday            As Byte
  Dim datLastDayOfYear          As Date

  bytWeek = DatePart("ww", datDate, vbMonday, vbFirstFourDays)

  If bytWeek = cbytLastWeekOfLeapYear Then
    bytISOThursday = Weekday(vbThursday, vbMonday)
    datLastDayOfYear = DateSerial(Year(datDate), 12, 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

  ISO_WeekNumber = bytWeek

End Function

替换 DatePart.

请注意,您还必须过滤年份,因为 ISO 周数 1 和 52/53 通常会跨越日历年边界。

附录:

这是 VBScript 版本,以防无法使用 VBA 版本:

Option Explicit

MsgBox ISO_WeekNumber(Date)

WScript.Quit


Function ISO_WeekNumber(ByVal Date1)

' Calculates and returns week number for date Date1 according to the ISO 8601:1988 standard.
' 2019, Gustav Brock, Cactus Data ApS, CPH.
' May be freely used and distributed.

  Const FirstWeekOfAnyYear = 1
  Const LastWeekOfLeapYear = 53

  Dim Week
  Dim ISOThursday
  Dim LastDayOfYear

  Week = DatePart("ww", Date1, vbMonday, vbFirstFourDays)

  If Week = LastWeekOfLeapYear Then
    ISOThursday = Weekday(vbThursday, vbMonday)
    LastDayOfYear = DateSerial(Year(Date1), 12, 31)
    If Weekday(LastDayOfYear, vbMonday) >= ISOThursday Then
      ' OK, week count of 53 is caused by leap year.
    Else
      ' Correct for VBA bug.
      Week = FirstWeekOfAnyYear
    End If
  End If

  ISO_WeekNumber = Week

End Function