TSQL计算登录和注销之间的总时间以及每个状态的时间

时间:2016-12-13 19:11:56

标签: sql sql-server tsql

我有SQL表如下(图1)

SQL Table

我正在尝试计算每个状态的时间差和登录和注销代理之间的总持续时间,如下所示。(图2)。我试图使用超前/滞后功能,但无法实现输出。你能帮忙吗?

Time In Each Stage and Final Desired Output

2 个答案:

答案 0 :(得分:-1)

下面的代码段可以帮助您开始:

;WITH TotalDuration as 
(
    SELECT  LogIN = Min(DateTime)
            ,LogOut =   Max(DateTime)
            ,AgentID
    FROM    YourTable
    Group BY AgentID

)

SELECT Duration = DATEDIFF(MINUTE, LogIN, LogOut)
        ,AgentId
FROM TotalDuration
ORDER BY  AgentId



--TimeInState = datediff(minute, [DateTime], LEAD([DateTime], 1) OVER (Partition BY AgentID ORDER BY [DateTime])) 

答案 1 :(得分:-1)

我想您知道如何使用min和max来获取总登录和注销时间......这里是您需要的LEAD和LAG。

with cte as(
    select
        agentid,
        eventtype,
        [DateTime], 
        datediff(mi,[DateTime],LEAD([DateTime]) over (partition by agentid order by [DateTime])) as [Time_in_state]
    from yourTable)

select
    agentid,
    eventtype,
    cast([DateTime] as Date) as TheDate,
    sum(Time_in_state) as TotalTime,
from cte
group by
    agentid,
    eventtype,
    cast([DateTime] as Date)
相关问题