我需要从下表中找出标志inserted处于活动状态(inserted = 1)时的情况。 date_from处于活动状态时,我需要显示间隔date_toinserted

表格如下:

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。

最佳答案

这是一种解决方案:

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

10-04 16:35