0

我有一个看起来像这样的查询......

SELECT tbl1.ProjectID, tbl1.EntryDate AS StartDate, tbl2.EntryDate AS EndDate
FROM checklist_entries tbl1
INNER JOIN checklist_entries tbl2
ON tbl1.ProjectID = tbl2.ProjectID
WHERE tbl1.ChecklistDay = (SELECT ChecklistDayMin FROM milestone_def WHERE MilestoneDefID = [@milestoneID])
AND tbl2.ChecklistDay = (SELECT ChecklistDayMax FROM milestone_def WHERE MileStoneDefID = [@milestoneID])

如您所见,这是一个自联接表,它返回一个 ProjectID (FK)、一个 StartDate 和 EndDate,它们都是表中的 EntryDate 列。为了返回记录,我需要传入一个整数值 [@milestoneID],它允许子查询返回 WHERE 子句所需的最小值和最大值。

由于此查询返回两个日期,我想了解如何在此查询的基础上构建并添加另一个列,该列返回的整数值 TotalDays(TotalDays 是工作日,周一至周五)由返回的 StartDate 和 EndDate 确定.

我可以找到一个查询来返回天数,但基本上我想在 ACCESS 中创建一个查询,允许我调用此查询(并传入 [@MilestoneID] 参数),并为返回的每条记录添加一列TotalDays 计数的结束。

4

1 回答 1

2

与我在这里的回答类似,您可以创建一个 VBA 函数来包含使用的工作日数

SELECT 
    ... ,
    CountWeekdays(tbl1.EntryDate, tbl2.EntryDate) AS TotalWeekdays 
FROM ...

只需在 Access 中新建一个Module并将以下代码粘贴到其中:

Public Function CountWeekdays(Date1 As Date, Date2 As Date) As Long
Dim StartDate As Date, EndDate As Date, _
        Weekdays As Long, i As Long
If Date1 > Date2 Then
    StartDate = Date2
    EndDate = Date1
Else
    StartDate = Date1
    EndDate = Date2
End If
Weekdays = 0
For i = 0 To DateDiff("d", StartDate, EndDate)
    Select Case Weekday(DateAdd("d", i, StartDate))
        Case 1, 7
            ' weekend - do nothing
        Case Else
            Weekdays = Weekdays + 1
    End Select
Next
CountWeekdays = Weekdays
End Function
于 2013-06-27T13:12:17.650 回答