繁体   English   中英

在timeStamp Access VBA / Excel上进行ORDER BY时发生汇总函数错误

[英]Aggregate function error when ORDER BY on timeStamp Access VBA / Excel

一个Access数据库包含一个机库的logData。 出于管理目的,我需要使用Excel生成一些图。 数据是使用VBA查询从Access获取的。 到现在为止还挺好。 除了dateStamp之外,还存储了一个星期编号(因为Access / Excel的ISO星期编号存在问题)。 但是,如果我提取2016年1月的数据,它不仅包含1-4周,还包含2016年的53周。 我想对它进行排序53、1、2、3、4。最后一步失败,并显示错误:

“您的查询未将指定的表达式Format $(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语句中,但是我不需要此列。

任何提示如何使星期正确排序?

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

该功能可以做到:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM