按照不同值的数字进行分组

时间:2015-12-08 18:42:18

标签: sql sql-server

ID | Week | BeginDate  | EndDate    | Value
1  | 38   | 14.9.2015  | 20.9.2015  | 100 
2  | 39   | 21.9.2015  | 27.9.2015  | 100 
3  | 40   | 28.9.2015  | 2.10.2015  | 100  
4  | 42   | 12.10.2015 | 18.10.2015 | 100
5  | 43   | 19.10.2015 | 25.10.2015 | 100
6  | 44   | 26.10.2015 | 31.10.2015 | 80 

如何将此记录分组为具有相同值的以下几周。 请求和结束日期也很重要。

在这种情况下,我期待3条记录:

StartDate  |  EndDate   | Value
14.9.2015  | 02.10.2015 | 100
12.10.2015 | 25.10.2015 | 100
26.10.2015 | 31.10.2015 | 80

1 个答案:

答案 0 :(得分:0)

这可能比现在更有效率,但我相信它会产生所需的输出。

; WITH CTE1 AS (
    SELECT T1.[Week]
        , T1.[BeginDate]
        , T1.[EndDate]
        , T1.[Value]
        , T2.[Week] [T2Week]
        , ROW_NUMBER() OVER (ORDER BY T1.[Week]) [RN]
    FROM tblName T1
    LEFT JOIN (SELECT [Week], [Value] FROM tblName) T2 ON T1.[Week] = T2.[Week] + 1 AND T1.[Value] = T2.[Value])
, CTE2 AS (SELECT T3.[Week]
        , T3.[BeginDate]
        , T3.[EndDate]
        , T3.[Value]
        , T4.[EndDate] [T2EndDate]
        , ROW_NUMBER() OVER (ORDER BY T3.[Week]) [RN]
    FROM CTE1 T3
    LEFT JOIN (SELECT [EndDate], [RN] FROM CTE1) T4 ON T3.[RN] = T4.[RN] + 1
    WHERE T3.[T2Week] IS NULL)
SELECT T5.[BeginDate]
    , ISNULL(T6.[T2EndDate], T5.[EndDate]) [T2EndDate]
    , T5.[Value]
FROM CTE2 T5
LEFT JOIN (SELECT [T2EndDate], [RN] FROM CTE2) T6 ON T5.[RN] = T6.[RN] - 1
-- ORDER BY T5.[RN]