标志处于活动状态时查找间隔

时间:2015-06-11 07:08:54

标签: sql sql-server tsql sql-server-2008-r2

我需要在下面的表格中找到标记inserted处于活动状态(inserted = 1)的情况。当date_from处于活动状态时,我需要向date_to显示间隔inserted

这是表格:

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

结果应该是这样的:

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

第一行date_fromNULL因为我们不知道inserted标志何时开始有效,但我们知道2014-04-17 10:39:59.790已完成。 最后一行date_toNULL,因为inserted标记仍然有效。

每一行都不能有两个标志相同;如果删除= 0则插入= 1,反之亦然。我使用的是SQL Server 2008R2。

1 个答案:

答案 0 :(得分:3)

这是一个解决方案:

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

输出:

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