ORDER BY on timeStamp访问VBA / Excel时的聚合函数错误

时间:2016-12-22 07:16:25

标签: excel-vba ms-access sql-order-by vba excel

Access数据库包含machinepark的logData。出于管理目的,我需要有一些使用Excel生成的数字。使用VBA查询从Access获取数据。到现在为止还挺好。 除了dateStamp之外,还存储了一个星期数(因为Access / Excel存在ISO周数问题)。但是,如果我提取2016年1月的数据,它不仅包含第1-4周,而且包含2016年第53周。我想把它分类为53,1,2,3,4。 最后一步失败,出现错误:

  

“您的查询不包含指定的表达式格式$(logData.dateStamp,'yyyy / mm')作为   聚合函数。“

使用下面的SQL查询:

TRANSFORM  sum((logData.hoursDay+logData.hoursNight)*60) 
SELECT reasons.reason FROM reasons 
INNER JOIN (logData INNER JOIN testRigs ON logData.machine = machines.ID) ON reasons.ID = logData.reason 
WHERE  Format$(logData.dateStamp,'mm') =  1  
AND machines.type = "A" 
GROUP BY reasons.reason 
ORDER BY Format$(logData.dateStamp,'yyyy/mm') DESC
PIVOT logData.week;

诸如AVG()和COUNT()之类的聚合函数可以在SELECT语句中,但我不需要此列。

有关如何正确分类周数的任何提示吗?

1 个答案:

答案 0 :(得分:0)

您不必存储周数,但在给定日期,您必须同时找到年份和周才能获得正确的排序。

这个功能可以:

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