Find intervals when flag was active

82 Views Asked by At

I need to find out from a table below when flag inserted was active (inserted = 1). I need to show interval date_from to date_to when inserted was active.

Here is the table:

no              dcr                     action deleted     inserted
--------------- ----------------------- ------ ----------- -----------
191005040000806 2014-04-17 10:39:59.790 U      1           0
191005040000806 2014-04-17 14:23:41.650 U      0           1
191005040000806 2015-03-25 09:46:03.270 U      1           0
191005040000806 2015-03-25 12:01:49.533 U      0           1

And result should be like this:

no              date_from               date_to
--------------- ----------------------- -----------------------
191005040000806 NULL                    2014-04-17 10:39:59.790
191005040000806 2014-04-17 14:23:41.650 2015-03-25 09:46:03.270
191005040000806 2015-03-25 12:01:49.533 NULL

In first row date_from is NULL because we don't know when inserted flag start being active, but we know that finished on 2014-04-17 10:39:59.790. In last row date_to is NULL because inserted flag is still active.

Each row can't have both flags the same; if deleted = 0 then inserted = 1 and vice versa. I'm using SQL Server 2008R2.

1

There are 1 best solutions below

0
On BEST ANSWER

Here is one solution:

DECLARE @t TABLE
    (
      no VARCHAR(20) ,
      dcr DATETIME ,
      inserted BIT
    )

INSERT  INTO @t
VALUES  ( '191005040000806', '2014-04-17 10:39:59.790', 0 ),
        ( '191005040000806', '2014-04-17 14:23:41.650', 1 ),
        ( '191005040000806', '2015-03-25 09:46:03.270', 0 ),
        ( '191005040000806', '2015-03-25 12:01:49.533', 1 )


;WITH cte AS(
            SELECT  no ,
                    ( SELECT    TOP 1 dcr
                      FROM      @t t2
                      WHERE     t2.no = t1.no AND t2.dcr < t1.dcr
                                AND t2.inserted = 1
                      ORDER BY dcr desc                  
                    ) AS date_from,
                   CASE WHEN dcr = '99991231' THEN NULL ELSE dcr end AS date_to    
            FROM  ( SELECT * FROM @t UNION ALL SELECT no, '99991231', 0 FROM @t GROUP BY no) t1
            WHERE t1.inserted = 0
)
SELECT no, date_from, MIN(date_to) AS date_to FROM cte
GROUP BY no, date_from

Output:

no              date_from                date_to
191005040000806 NULL                     2014-04-17 10:39:59.790
191005040000806 2014-04-17 14:23:41.650  2015-03-25 09:46:03.270
191005040000806 2015-03-25 12:01:49.533  NULL