SQL - 获取上一行并使用条件复制它

时间:2018-05-02 12:23:44

标签: mysql

我有一张如下表格

ID      status          message     set  
---------------------------------------
1       Completed       step1       1  
2       Completed       step2       1  
3       Failed          step3       1  
4       Completed       step1       2  
5       Completed       step2       2  
6       Failed          step3       2  

对于每一组,如果步骤失败,我需要复制上一步并创建一个状态为" New"的新行。 所以我的桌子需要看起来像

ID      status          message     set  
---------------------------------------
1       Completed       step1       1  
2       Completed       step2       1  
3       Failed          step3       1  
4       Completed       step1       2  
5       Completed       step2       2  
6       Failed          step3       2  
7       New             step2       1  
8       New             step2       2  

有人可以帮我处理SQL查询吗? 我一直试图用Lag和db_cursor写一些东西,但到目前为止还没有运气。我将继续努力,如果有人指出我正确的方向,那将是有帮助的。

1 个答案:

答案 0 :(得分:0)

我到达了下面的解决方案。

DECLARE @set INT,
        @id  INT

--create a temporary table collecting the set value for the rows with failed message

IF OBJECT_ID(N'tempdb.dbo.#failList') IS NOT NULL
DROP TABLE #failList
SELECT  set
INTO    #failList
FROM    my_table WITH (NOLOCK)
WHERE  status = 'Failed'
and message = 'step3'

--loop over the failList and match the step to get the previous row and duplicate it

WHILE EXISTS (SELECT TOP 1 1 FROM #failList)
BEGIN
SELECT TOP 1 @step = step
FROM    #failList

INSERT  INTO my_table (status, message, set)
SELECT  'New', message, set]
FROM    my_table d WITH (NOLOCK)
    WHERE   d.set = @set
    and message = 'step2'

DELETE FROM #failList WHERE set = @set      
END