2016-12-22 25 views
0

Access数据库包含machinepark的logData。为了管理目的,我需要一些使用Excel生成的数字。使用VBA查询从Access获取数据。到现在为止还挺好。 除了dateStamp之外,还会存储一个星期编号(因为Access/Excel对ISO星期编号有问题)。但是,如果我提取2016年1月的数据,那么它不仅包含2016年的第1-4周和第53周。我要排序它53,1,2,3,4, 这最后一步失败,出现错误:时间戳上的ORDER BY访问VBA/Excel时的聚合函数错误

"Your query does not include the specified expression Format$(logData.dateStamp,'yyyy/mm') as part of an aggregate function."

与下面的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语句中,但我不需要这个列。

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

+0

如果你不能在_Group By_节的表情,你将不得不删除其与_Order By_部分和_Pivot_不上一周,但年 - 和周。见下面的功能。 – Gustav

回答

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