Access 2007:如何在中进行周开始和周末并在结果中显示周结束日期

Access 2007: How to do weekstart and weekending and have the weekending dates show on result

好的,我有一个查询需要在输出中显示所有周末日期以及计算从星期日开始到星期六结束的一周内审查的 callIDs 的计数?

目前我正在插入开始日期和结束日期,但这不会在输出中累积周末。

意思是我想在输出中看到的是:

您将不得不使用一些 Access SQL 函数:IIF()Weekday()DateAdd()。本质上就是要找到一个日期的weekday number(1-7,对应Sun-Sat),然后加上对应的值,得到所有日期到return星期六的日期:

SELECT [Coach].[LastName] & ", " & [Coach].[FirstName] AS CoachName, 
     Count(S.CallId) AS [CountOfSupervisors], tblLocations.LocationName,  
     IIF(Weekday(S.DateScored) = 7, S.DateScored,
     IIF(Weekday(S.DateScored) = 6, DateAdd('d', 1, S.DateScored),
     IIF(Weekday(S.DateScored) = 5, DateAdd('d', 2, S.DateScored),
     IIF(Weekday(S.DateScored) = 4, DateAdd('d', 3, S.DateScored),
     IIF(Weekday(S.DateScored) = 3, DateAdd('d', 4, S.DateScored),
     IIF(Weekday(S.DateScored) = 2, DateAdd('d', 5, S.DateScored),
     IIF(Weekday(S.DateScored) = 1, DateAdd('d', 6, S.DateScored), Null))))))) As EndOfWeek

FROM tblLocations INNER JOIN (tblScores AS S 
INNER JOIN tblEmployees AS Coach ON S.CoachId = Coach.ID) ON tblLocations.ID = S.LocationId 
WHERE (((tblLocations.LocationName IN ('Nashville','Solon','San Antonio','Phoenix') AND 
        ((Coach.Source)='Supervisor') AND ((S.Completed)=Yes) AND 
        ((S.DateScored)>=[Start Date] And (S.DateScored)<=[End Date]))

GROUP BY [Coach].[LastName] & ", " & [Coach].[FirstName], tblLocations.LocationName, 
     Coach.Source, S.Completed, 
     IIF(Weekday(S.DateScored) = 7, S.DateScored,
     IIF(Weekday(S.DateScored) = 6, DateAdd('d', 1, S.DateScored),
     IIF(Weekday(S.DateScored) = 5, DateAdd('d', 2, S.DateScored),
     IIF(Weekday(S.DateScored) = 4, DateAdd('d', 3, S.DateScored),
     IIF(Weekday(S.DateScored) = 3, DateAdd('d', 4, S.DateScored),
     IIF(Weekday(S.DateScored) = 2, DateAdd('d', 5, S.DateScored),
     IIF(Weekday(S.DateScored) = 1, DateAdd('d', 6, S.DateScored), Null)))))));

或者,这是一个不那么冗长的解决方案,由@HansUp 确定,没有嵌套的 IIF() 语句:

SELECT [Coach].[LastName] & ", " & [Coach].[FirstName] AS CoachName, 
    Count(S.CallId) AS [CountOfSupervisors], tblLocations.LocationName,  
    DateAdd('d', IIf(S.DateScored Is Null, 0, 7 - Weekday(S.DateScored)), S.DateScored) As EndOfWeek

FROM tblLocations INNER JOIN (tblScores AS S 
INNER JOIN tblEmployees AS Coach ON S.CoachId = Coach.ID) ON tblLocations.ID = S.LocationId 
    WHERE (((tblLocations.LocationName IN ('Nashville','Solon','San Antonio','Phoenix') AND 
    ((Coach.Source)='Supervisor') AND ((S.Completed)=Yes) AND 
    ((S.DateScored)>=[Start Date] And (S.DateScored)<=[End Date]))

GROUP BY [Coach].[LastName] & ", " & [Coach].[FirstName], tblLocations.LocationName, 
    Coach.Source, S.Completed, 
    DateAdd('d', IIf(S.DateScored Is Null, 0, 7 - Weekday(S.DateScored)), S.DateScored);

您会注意到我调整了您的一些代码。您可以将所有 HAVING 语句移动到 WHERE 子句中(HAVING 在表示聚合时使用 - Count、Sum、Avg、First、Last)。此外,您可以对多个 OR 条件使用 IN() 子句。希望这有效!