Calculating time difference between activity timestamps in a query

爱⌒轻易说出口 提交于 2019-12-06 12:01:33

You can use a correlated subquery to fetch the next timestamp for each row.

SELECT
    i.status,
    i.timestamp,
    (
        SELECT Min([timestamp])
        FROM importedData
        WHERE [timestamp] > i.timestamp
    ) AS next_timestamp
FROM importedData AS i
WHERE i.timestamp BETWEEN #2013-11-29 06:00:00#
    AND #2013-11-29 18:00:00#;

Then you can use that query as a subquery in another query where you compute the duration between timestamp and next_timestamp. And then use that entire new query as a subquery in a third where you GROUP BY status and compute the total duration for each status.

Here's my version which I tested in Access 2007 ...

SELECT
    sub2.status,
    Format(Sum(Nz(sub2.duration,0)), 'hh:nn:ss') AS SumOfduration
FROM
    (
        SELECT
            sub1.status,
            (sub1.next_timestamp - sub1.timestamp) AS duration
        FROM
            (
                SELECT
                    i.status,
                    i.timestamp,
                    (
                        SELECT Min([timestamp])
                        FROM importedData
                        WHERE [timestamp] > i.timestamp
                    ) AS next_timestamp
                FROM importedData AS i
                WHERE i.timestamp BETWEEN #2013-11-29 06:00:00#
                    AND #2013-11-29 18:00:00#
            ) AS sub1
    )  AS sub2
GROUP BY sub2.status;

If you run into trouble or need to modify it, break out the innermost subquery, sub1, and test that by itself. Then do the same for sub2. I suspect you will want to change the WHERE clause to use parameters instead of hard-coded times.

Note the query Format expression would not be appropriate if your durations exceed 24 hours. Here is an Immediate window session which illustrates the problem ...

' duration greater than one day:
? #2013-11-30 02:00# - #2013-11-29 01:00#
 1.04166666667152 
' this Format() makes the 25 hr. duration appear as 1 hr.:
? Format(#2013-11-30 02:00# - #2013-11-29 01:00#, "hh:nn:ss")
01:00:00

However, if you're dealing exclusively with data from 12 hr. shifts, this should not be a problem. Keep it in mind in case you ever need to analyze data which spans more than 24 hrs.

If subqueries are unfamiliar, see Allen Browne's page: Subquery basics. He discusses correlated subqueries in the section titled Get the value in another record.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!