Group close numbers

后端 未结 3 1611
粉色の甜心
粉色の甜心 2021-02-08 08:49

I have a table with 2 columns of integers. The first column represents start index and the second column represents end index.

START END
1     8
9     13
14    2         


        
3条回答
  •  不要未来只要你来
    2021-02-08 09:36

    You could use a number table to solve this problem. Basically, you first expand the ranges, then combine subsequent items in groups.

    Here's one implementation:

    WITH data (START, [END]) AS (
      SELECT  1,  8 UNION ALL
      SELECT  9, 13 UNION ALL
      SELECT 14, 20 UNION ALL
      SELECT 20, 25 UNION ALL
      SELECT 30, 42 UNION ALL
      SELECT 42, 49 UNION ALL
      SELECT 60, 67
    ),
    expanded AS (
      SELECT DISTINCT
        N = d.START + v.number
      FROM data d
        INNER JOIN master..spt_values v ON v.number BETWEEN 0 AND d.[END] - d.START
      WHERE v.type = 'P'
    ),
    marked AS (
      SELECT
        N,
        SeqID = N - ROW_NUMBER() OVER (ORDER BY N)
      FROM expanded
    )
    SELECT
      START = MIN(N),
      [END] = MAX(N)
    FROM marked
    GROUP BY SeqID
    

    This solution uses master..spt_values as a number table, for expanding the initial ranges. But if (all or some of) those ranges may span more than 2048 (subsequent) values, then you should define and use your own number table.

提交回复
热议问题