计算连续日期之间的持续时间

时间:2014-06-04 13:29:59

标签: sql-server stored-procedures

希望你能帮助我解决这个问题。我想根据事件计算连续日期时间之间的持续时间。这是我的表

**LoginID     Datetime     EventID**

*3399   5/19/2014 12:55:53  2
3399    5/19/2014 13:00:07  3*
3399    5/19/2014 13:58:52  4
3399    5/19/2014 13:58:55  5
*3399   5/19/2014 14:31:15  2
3399    5/19/2014 14:46:16  3*
3399    5/19/2014 14:46:44  4
3399    5/19/2014 14:46:47  5
*3399   5/19/2014 16:43:28  2
3399    5/19/2014 17:43:27  3*
*3399   5/19/2014 19:31:13  2
3399    5/19/2014 19:46:13  3*
3399    5/19/2014 21:06:38  4

我想计算从事件2转换到任何其他事件时所有持续时间的总和(以秒为单位)。上述数据的总持续时间为: 5654秒

感谢任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:0)

谢谢大家。我能够通过 RANK()OVER PARTITION BY

来实现它

这是:

WITH LOGIN_LOGOUT_STATES
AS (
  SELECT RES.resourcename
      ,ASD.eventdatetime
      ,ASD.eventtype
      ,RANK() OVER (
          PARTITION BY RES.resourcename ORDER BY RES.resourcename
              ,ASD.eventdatetime
          ) AS rn
  FROM agentstatedetail ASD
  JOIN resource RES ON ASD.agentid = RES.ResourceID
  WHERE ASD.eventdatetime  BETWEEN @StartDate
                  AND @EndDate
      AND ASD.agentid IN (
          SELECT ResourceID
          FROM @myFinalTable
          )           
  )
  ,LOGIN_STATE_DIFFERENCE
AS (
  SELECT C1.resourcename AS [AGENT_NAME]
      ,CONVERT(DATE, C2.eventdatetime) AS [DATE]
      ,DATEDIFF(SECOND, C2.eventdatetime, C1.eventdatetime) AS [DURATION]
  FROM LOGIN_LOGOUT_STATES AS C1
  INNER JOIN LOGIN_LOGOUT_STATES AS C2 ON C1.resourcename = C2.resourcename AND C1.rn = C2.rn + 1
  WHERE C1.eventtype = 2
  )
  SELECT * FROM LOGIN_STATE_DIFFERENCE