访问:计算行

时间:2015-06-16 19:59:13

标签: sql ms-access

以下是我在代理进行系统更改时从系统跟踪中在MS Access中使用的数据:

|agentid|eventtype|reasoncode|eventdatetimelocal   |
|1830   |2        |32762     |01/01/2014 7:11:44 PM|
|1830   |3        |0         |01/01/2014 7:13:46 PM|
|1830   |2        |32762     |01/01/2014 7:14:55 PM|
|1833   |2        |0         |01/01/2014 7:11:35 PM|
|1833   |3        |32762     |01/01/2014 7:13:25 PM| 

我需要确定代理之间行之间经过的秒数。我还想保留eventtype和reasoncode的细节。

我尝试加入一个subqry但它不起作用:

SELECT sub1.agentid, 
       sub1.eventtype, 
       sub1.reasoncode,
       sub1.eventdatetimelocal, 
       (sub1.next_timestamp-sub1.eventdatetimelocal) AS duration
FROM (SELECT i.agentid, 
      eventdatetimelocal, 
      eventtype, 
      reasoncode, (SELECT
                        Min([eventdatetimelocal]) 
                   FROM state_detail_tbl 
                   WHERE [eventdatetimelocal] > i.eventdatetimelocal
                   ) AS next_timestamp 
     FROM state_detail_tbl AS i 
     WHERE i.eventdatetimelocal BETWEEN #01/01/2014# AND #01/31/2014#
)  AS sub1;

2 个答案:

答案 0 :(得分:0)

您可以尝试此查询

SELECT sub1.agentid, 
       sub1.eventtype, 
       sub1.reasoncode,
       sub1.eventdatetimelocal, 
       (SELECT TOP 1 sub2.eventdatetimelocal - sub1.eventdatetimelocal 
        FROM state_detail_tbl AS sub2 
        WHERE sub1.agentid=sub2.agentid
              AND sub2.eventdatetimelocal > sub1.eventdatetimelocal 
        ORDER BY sub2.eventdatetimelocal) AS duration

FROM state_detail_tbl sub1
WHERE (SELECT TOP 1 eventdatetimelocal 
       FROM state_detail_tbl AS s3 
       WHERE sub1.agentid=s3.agentid 
             AND s3.eventdatetimelocal > sub1.eventdatetimelocal) Is Not Null
AND sub1.eventdatetimelocal BETWEEN #01/01/2014# AND #01/31/2014#
ORDER BY sub1.agentid, sub1.eventdatetimelocal;

答案 1 :(得分:0)

我从下面的查询中收到一条错误,说明"这个查询最多只能返回一行"。但是查询以及这个参考:Calculating time difference between activity timestamps in a query给了我我需要的内容,我将在下面列出以供参考。我认为我的初始需求过于宽泛,因此我简化了查询以返回将时间戳提升到前一行所需的最小数据。我可以使用datediff再次进行查询,以找出秒数。这需要一段时间来处理,但它可以工作,如果需要可以在一夜之间运行。

SELECT i.agentid, i.eventtype, i.reasoncode, eventdatetimelocal, (SELECT
Min([eventdatetimelocal]) FROM state_detail_subqry WHERE agentid = i.agentid
AND [eventdatetimelocal]>i.[eventdatetimelocal]) AS next_timestamp
FROM state_detail_subqry AS i
ORDER BY agentid, eventdatetimelocal;