TSQL查询有助于计算位标志从0变为1的记录之间的时间差

时间:2018-01-24 16:41:06

标签: sql sql-server datetime datediff date-arithmetic

我需要一些TSQL查询的帮助。我需要计算下表中的位标志的总时间=' 1'。我的拦截器是有数百万的潜在记录,我需要以一个“LogDate”为基础。柱。所以我假设我需要创建一个" Time Start"当位标志从0变为1并且"时间结束时#34;当它从1回到0然后迭代并做一个约会。

我的挑战只有基本的SQL知识,这是我的驾驶室。任何可以分享的魔法?

需要对这些开始/结束进行分组,并对总hh:mm:ss

进行算术运算

示例数据:

LogDate             StateBit
12/25/17 6:41:30    0
12/25/17 6:42:45    1 <-- Start time 
12/25/17 6:44:25    1
12/25/17 6:44:40    1
12/25/17 6:44:55    1
12/25/17 6:56:11    1
12/25/17 7:00:19    1
12/25/17 7:00:34    1
12/25/17 7:02:04    1
12/25/17 7:02:43    1
12/25/17 7:02:58    1 <-- End time 
12/25/17 7:03:15    0

3 个答案:

答案 0 :(得分:2)

您可以将群组标识为:

select t.*,
       sum(case when prev_bit = bit then 0 else 1 end) over (order by dt) as grp
from (select t.*,
             lag(bit) over (order by dt) as prev_bit
      from t
     ) t;

然后您可以累积每个组的句点:

select min(dt), max(dt), bit
from (select t.*,
             sum(case when prev_bit = bit then 0 else 1 end) over (order by dt) as grp
      from (select t.*,
                   lag(bit) over (order by dt) as prev_bit
            from t
           ) t
     ) t
group by grp, bit;

我认为您可以使用此信息来获得所需的总跨​​度。

答案 1 :(得分:1)

我认为你可以这样使用

-- You need to have changed states rows and dates of before states in one row (the best choice is first rows of changed states
;with MakeLag as (select *,Lag(StateBit)over(order by id) ld,Lag(LogDate)over(order by LogDate)lDt  from #t )

--Next Step is to calculate seconds between this Two dates
,CalcSeconds as(select *,datediff(second,lDt,LogDate) as Dif from MakeLag where ld<>StateBit)

--And for finish you need to change these datediffs to "dd hh:mm:ss"
select *, CAST(FLOOR(Dif / 86400) AS VARCHAR(10))+'d ' +CONVERT(VARCHAR(8), DATEADD(SECOND, Dif, '19000101'), 8) as FinDiff from CalcSeconds

答案 2 :(得分:0)

我的建议很简单,可能误解了你的需要,但是如果根据stateBit进行过滤,只需减去最小值和最大值。

select max(logdate) - min (logdate) from tbl where StateBit = 1;