在SQL中查找组中的连续数字

时间:2018-03-24 23:26:37

标签: sql sql-server

我需要在SQL中找到组中的连续数字。

实施例: 表1

   id  | group   | result (group id)
-------+---------+-----------------------------
    1  |   a     |  1
    2  |   a     |  1
    3  |   a     |  1
    4  |   a     |  1
    5  |   a     |  1
    8  |   a     |  2
   10  |   a     |  3
   13  |   a     |  4
   14  |   a     |  4
   15  |   a     |  4
   16  |   a     |  4
   20  |   a     |  5
    2  |   b     |  1
    3  |   b     |  1
    4  |   b     |  1
    5  |   b     |  1
    8  |   b     |  2
   10  |   b     |  3
   13  |   b     |  4
   16  |   b     |  5
   20  |   b     |  6

我找到了这个解决方案(Group by numbers that are in sequence),但我无法将其保留为群组

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 

2 个答案:

答案 0 :(得分:2)

使用lag()窗口函数有另一种解决方案:

select id, grp, sum(mark) over (partition by grp order by id)
from (
  select 
    id, grp, 
    case when id - 1 = lag(id) over (partition by grp order by id) then 0 else 1 end as mark
  from my_table
  ) s;

https://stackoverflow.com/a/45959000/7433423

中测试

答案 1 :(得分:2)

也许是另一种选择

示例

Select id
      ,[group]
      ,result = dense_rank() over (Partition by [group] order by grp)
 From ( 
       Select *
             ,Grp = id - row_number() over (Partition by [group] order by id)
        From  YourTable
       ) A
 Order by [group],id

<强>返回

id  group   result
1   a       1
2   a       1
3   a       1
4   a       1
5   a       1
8   a       2
10  a       3
13  a       4
14  a       4
15  a       4
16  a       4
20  a       5
2   b       1
3   b       1
4   b       1
5   b       1
8   b       2
10  b       3
13  b       4
16  b       5
20  b       6