Merging data in a single SQL table without a Cursor

后端 未结 4 1295
-上瘾入骨i
-上瘾入骨i 2021-01-31 19:51

I have a table with an ID column and another column with a number. One ID can have multiple numbers. For example

ID | Number
 1 |  25
 1 |  26
 1 |  30
 1 |  24
         


        
4条回答
  •  误落风尘
    2021-01-31 20:39

    The key observation is that a sequence of numbers minus another sequence is a constant. We can generate another sequence using row_number. This identifies all the groups:

    select id, MIN(number) as low, MAX(number) as high
    from (select t.*,
                 (number - ROW_NUMBER() over (partition by id order by number) ) as groupnum
          from t
         ) t
    group by id, groupnum
    

    The rest is just aggregation.

提交回复
热议问题