Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL—同一列中的时间差_Sql_Sql Server_Datetime_Window Functions_Gaps And Islands - Fatal编程技术网

SQL—同一列中的时间差

SQL—同一列中的时间差,sql,sql-server,datetime,window-functions,gaps-and-islands,Sql,Sql Server,Datetime,Window Functions,Gaps And Islands,我需要计算事件“PAUSEALL”和“UNPAUSEALL”之间的时间差(以秒为单位) 因为我面临两个问题,所以我没能成功: 所有“事件”的“日期时间”在同一列中 事件“PAUSEALL”和“UNPAUSEALL”的名为“#queue_stats_id”的标识字段之间的距离不遵循顺序 以以下格式获得结果将对我有很大帮助: 提前谢谢你 您可以使用窗口功能。假设暂停和取消暂停事件始终正确交错: select * from ( select t.*, da

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

因为我面临两个问题,所以我没能成功:

  • 所有“事件”的“日期时间”在同一列中
  • 事件“PAUSEALL”和“UNPAUSEALL”的名为“#queue_stats_id”的标识字段之间的距离不遵循顺序
  • 以以下格式获得结果将对我有很大帮助:


    提前谢谢你

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

    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.*, datediff(second, datetime, 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'