SQL-同一列中的时差

问题描述

我需要计算事件“ PAUSEALL”和“ UNPAUSEALL”之间的时间差(以秒为单位)。

由于遇到两个问题,我无法做到这一点:

  1. “日期时间”在所有“事件”的同一列中
  2. 事件“ PAUSEALL”和“ UNPAUSEALL”的名为“#queue_stats_id”的标识字段之间的距离不遵循顺序。

Actual_SQL_Server_Table

采用以下格式的结果对我有很大帮助:

Results

提前谢谢!

解决方法

您可以使用窗口功能。假设暂停和取消暂停事件始终正确交错:

select *
from (
    select 
        t.*,datediff(second,datetime,min(case when event = 'UNPAUSEALL' then datetime end) over(
                partition by qagent
                order by datetime
                rows between current row and unbounded following
            )
        ) duration_second
    from mytable t
) t
where event = 'PAUSEALL'

这个想法是在以下几行中搜索最近的暂停事件,并获取相应的日期。

另一方面,如果可能有连续的暂停或取消暂停事件,则情况有所不同。我们需要首先建立相邻行的组。一种选择是使用对每个暂停事件递增的窗口计数:

select t.*,next_unpause_datetime) duration_second
from (
    select t.*,min(case when event = 'UNPAUSEALL' then datetime end) over(partition by qagent,grp) next_unpause_datetime
    from (
        select t.*,sum(case when event = 'PAUSEALL' then 1 else 0 end) over(partition by qagent order by datetime) grp
        from mytable t
    ) t
) t
where event = 'PAUSEALL'