在这个问题中有两种记录:
记录 [StartTime] 和 [StopTime] 在同一月份的位置,以及
记录他们不在的地方。
计算第一种情况的经过时间很容易:
SELECT
Staff,
Month([StartTime]) AS WorkMonth,
DateDiff("n", [StartTime], [EndTime]) AS MinutesWorked
FROM WorkLog
WHERE Month([EndTime])=Month([StartTime])
计算跨越一个月边界的记录的经过时间是一个由两部分组成的过程:
(i) 获取前一个月的经过时间
SELECT
Staff,
Month([StartTime]) AS WorkMonth,
DateDiff("n", [StartTime], DateSerial(Year([StartTime]), Month([StartTime]) + 1, 1)) AS MinutesWorked
FROM WorkLog
WHERE Month([EndTime])>Month([StartTime])
(ii) 获取下个月的经过时间
SELECT
Staff,
Month([EndTime]) AS WorkMonth,
DateDiff("n", DateSerial(Year([EndTime]), Month([EndTime]), 1), [EndTime]) AS MinutesWorked
FROM WorkLog
WHERE Month([EndTime])>Month([StartTime])
因此,要获得总数,我们只需将所有三个查询联合起来,并将它们包装在一个聚合查询中以执行 SUM()
SELECT WorkMonth, Staff, SUM(MinutesWorked) AS TotalMinutes
FROM
(
SELECT
Staff,
Month([StartTime]) AS WorkMonth,
DateDiff("n", [StartTime], [EndTime]) AS MinutesWorked
FROM WorkLog
WHERE Month([EndTime])=Month([StartTime])
UNION ALL
SELECT
Staff,
Month([StartTime]) AS WorkMonth,
DateDiff("n", [StartTime], DateSerial(Year([StartTime]), Month([StartTime]) + 1, 1)) AS MinutesWorked
FROM WorkLog
WHERE Month([EndTime])>Month([StartTime])
UNION ALL
SELECT
Staff,
Month([EndTime]) AS WorkMonth,
DateDiff("n", DateSerial(Year([EndTime]), Month([EndTime]), 1), [EndTime]) AS MinutesWorked
FROM WorkLog
WHERE Month([EndTime])>Month([StartTime])
)
GROUP BY WorkMonth, Staff
那会回来的...
WorkMonth Staff TotalMinutes
--------- ----- ------------
3 B 210
4 B 225
...Format()
如果您想调整月份的格式(例如,作为文本)或总时间(例如,作为“hh:nn”),您可以添加函数。