sqlsql-servergaps-and-islands

Roll Up with column changes


Table below - order by [low],[high]

Group Section Low High
A 01 01 10
A 01 11 15
A 01 18 18
A 01 19 25
A 02 26 30
A 02 31 32
A 01 33 40
A 01 41 41

By using the table above, I would like to create another table (the example below), so every time before the [Section] change, I would like the get the MIN(Low) and MAX(High).

Group Section Low High
A 01 01 25
A 02 26 32
A 01 33 41

Obviously, this is too simple and would not work

select [group], [section], min([low]), max([high])
from table
group by [group], [section]

Solution

  • You could also find the different groups by partitioning those with various combinations and finding their difference.

    ;WITH GroupedData AS (
        SELECT 
            GroupName,
            Section,
            [Low],
            [High],
            ROW_NUMBER() OVER (PARTITION BY GroupName ORDER BY [Low]) 
            - ROW_NUMBER() OVER (PARTITION BY GroupName, Section ORDER BY [Low]) AS GroupingKey
        FROM DataTable
    )
    --select * from GroupedData;
    SELECT 
        GroupName,
        Section,
        MIN([Low]) AS [Low],
        MAX([High]) AS [High]
    FROM GroupedData
    GROUP BY GroupName, Section, GroupingKey
    ORDER BY 1, 3;
    

    Result Grid:

    enter image description here