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.
Here is one solution:
Output: