0

我的表:

Date    Col1    Col2    Col3    flag
12/29/2014  AA  NULL    NULL    NULL
12/30/2014  AA  NULL    NULL    NULL
12/31/2014  AA  NULL    NULL    NULL
1/1/2015    AA  XX      CC      NULL
1/2/2015    AA  XX      CC      NULL
1/3/2015    AA  XX      CC      NULL
1/4/2015    AA  NULL    NULL    NULL
1/5/2015    AA  NULL    NULL    NULL
1/6/2015    AA  NULL    NULL    NULL
1/7/2015    AA  NULL    NULL    NULL
1/8/2015    AA  NULL    NULL    NULL
1/9/2015    AA  XX      CC      NULL
1/10/2015   AA  XX      CC      NULL
1/10/2015   AA  XX      CC      NULL
1/11/2015   AA  NULL    NULL    NULL
1/12/2015   AA  XX      CC      NULL
1/13/2015   AA  XX      CC      NULL
1/14/2015   AA  NULL    NULL    NULL
1/15/2015   AA  NULL    NULL    NULL
1/16/2015   AA  NULL    NULL    NULL
1/17/2015   AA  NULL    NULL    NULL
1/18/2015   AA  NULL    NULL    NULL
1/19/2015   AA  NULL    NULL    NULL
1/20/2015   AA  NULL    NULL    NULL
1/21/2015   AA  NULL    NULL    NULL
1/22/2015   AA  NULL    NULL    NULL
1/23/2015   AA  NULL    NULL    NULL
1/24/2015   AA  NULL    NULL    NULL
1/25/2015   AA  NULL    NULL    NULL
1/26/2015   AA  NULL    NULL    NULL
1/27/2015   AA  NULL    NULL    NULL
1/28/2015   AA  NULL    NULL    NULL
1/29/2015   AA  XX      DD      NULL
1/30/2015   AA  XX      DD      NULL
1/31/2015   AA  NULL    NULL    NULL

Col3更改日期的组合时Col1Col2我需要更新/设置标志。

例如:Between1/3/20151/9/2015的值Col3是相同的 ( CC) 所以我需要在until0之间的所有日子里设置标志。1/4/20151/8/2015

之间1/13/20151/29/2015的值Col3CC变为DD。所以我需要在直到1之间的所有日子里设置标志。1/14/20151/28/2015

它已经成为我的脑筋急转弯,请任何专家帮助?

4

1 回答 1

0

我认为你需要newFlag这样的:

SELECT *,   CASE 
                WHEN Col3 IS NULL AND (PreCol3 = NextCol3) THEN 1
                WHEN Col3 IS NULL AND (PreCol3 <> NextCol3) THEN 2
                ELSE Null
            END As newFlag 
FROM (
    SELECT *
        , (SELECT TOP 1 ci.Col3 FROM yourTable ci 
            WHERE ci.[Date] = (SELECT Max(cii.[Date]) FROM yourTable cii
                                WHERE cii.Col3 IS NOT NULL AND cii.[Date] < c.[Date])) As PreCol3
         , (SELECT TOP 1 ci.Col3 FROM yourTable ci 
            WHERE ci.[Date] = (SELECT Min(cii.[Date]) FROM yourTable cii
                                WHERE cii.Col3 IS NOT NULL AND cii.[Date] > c.[Date])) As NextCol3
    FROM yourTable c
    ) yt
于 2015-04-18T07:40:31.533 回答