How to group ranged values using SQL Server

前端 未结 2 1660
清酒与你
清酒与你 2021-01-16 09:10

I have a table of values like this

978412, 400
978813, 20
978834, 50
981001, 20

As you can see the second number when added to the first is

2条回答
  •  鱼传尺愫
    2021-01-16 09:17

    From the article that Josh posted, here's my take (tested and working):

    SELECT
        MAX(t1.gapID) as gapID,
        t2.gapID-MAX(t1.gapID)+t2.gapSize as gapSize
        -- max(t1) is the specific lower bound of t2 because of the group by.
    FROM
      ( -- t1 is the lower boundary of an island.
        SELECT gapID
        FROM gaps tbl1 
        WHERE
          NOT EXISTS(
            SELECT *
            FROM gaps tbl2 
            WHERE tbl1.gapID = tbl2.gapID + tbl2.gapSize + 1
          )
      ) t1
      INNER JOIN ( -- t2 is the upper boundary of an island.
        SELECT gapID, gapSize
        FROM gaps tbl1 
        WHERE
          NOT EXISTS(
            SELECT * FROM gaps tbl2 
            WHERE tbl2.gapID = tbl1.gapID + tbl1.gapSize + 1
          )
      ) t2 ON t1.gapID <= t2.gapID -- For all t1, we get all bigger t2 and opposite.
    GROUP BY t2.gapID, t2.gapSize
    

提交回复
热议问题