2016-12-22 24 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