Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by numbers that are in sequence

I have some data like this:

row    id
1      1
2      36
3      37
4      38
5      50
6      51

I would like to query it to look like this:

 row    id    group
 1      1     1
 2      36    2
 3      37    2
 4      38    2
 5      50    3
 6      51    3

... so that I can GROUP BY where the numbers are consecutively sequential.

Also, looping/cursoring is out of the question since I'm working with a pretty large set of data, thanks.

like image 965
Gagege Avatar asked Dec 21 '22 11:12

Gagege


1 Answers

;WITH firstrows AS
(
    SELECT id, ROW_NUMBER() OVER (ORDER BY id) groupid
    FROM Table1 a
    WHERE id - 1 NOT IN (SELECT b.id FROM Table1 b)
)
SELECT id, 
    (
        SELECT MAX(b.groupid)
        FROM firstrows b
        WHERE b.id <= a.id
    ) groupid
FROM Table1 a
like image 128
Anthony Faull Avatar answered Dec 28 '22 08:12

Anthony Faull