识别 SQL Server 列表中的连续数字组

问题描述 投票:0回答:2

样本数据

Column1
-------
   1
   4
  10
  11
  12
  18
  25
  27
  28
  29
  33
  36

预期产出

Continuous Numbers
------------------
     10
     11
     12
     27
     28
     29

count(coutinous numbers)
------------------------
       2 
sql-server-2012
2个回答
0
投票

您需要使用超前和滞后函数: 请参阅此链接:SQL Server 2012 函数 - 超前和滞后

-- Declare Table to test : 
       DECLARE @Temp TABLE (Number INT) 
        INSERT INTO @Temp VALUES ( 1 ) , ( 4 ) , ( 10 ) ,( 11 ) ,( 12 ) ,
                                     ( 18 ) ,( 25 ) ,( 27 ) ,( 28 ) ,( 29 ) ,
                                     ( 33 ) ,( 36 );

---------------------------------------------------------------------------------
-- To return the count 

SELECT COUNT(1) CoutinousNumberCount
FROM   (   SELECT Number ,
                  LAG(Temp.Number, 1) OVER ( ORDER BY Temp.Number ) AS PreviousNumber ,
                  LEAD(Temp.Number, 1) OVER ( ORDER BY Temp.Number ) AS NextNumber ,
                  CASE WHEN LAG(Temp.Number, 1) 
                            OVER ( ORDER BY Temp.Number )  = Number - 1 THEN
                           0
                       ELSE 1
                  END AS Separator
           FROM   @Temp AS Temp 
       ) AS result
WHERE  (result.PreviousNumber = result.Number - 1
       OR result.NextNumber = result.Number + 1)
       AND Separator = 1;

-----------------------------------------------------------------------------------------
-- And to return the list:
SELECT Number
FROM   (   SELECT Number ,
                  LAG(Temp.Number, 1) OVER ( ORDER BY Temp.Number ) AS PreviousNumber ,
                  LEAD(Temp.Number, 1) OVER ( ORDER BY Temp.Number ) AS NextNumber 
           FROM   @Temp AS Temp
       ) AS result
WHERE  result.PreviousNumber = result.Number - 1
       OR result.NextNumber = result.Number + 1;

0
投票

使用 SQL-Server 2012,您可以使用

LAG()
LEAD()

DECLARE @tbl TABLE(Column1 INT)
INSERT INTO @tbl VALUES(1),(4),(10),(11),(12),(18),(25),(27),(28),(29),(33),(36);

WITH Neighbours AS
(
    SELECT Column1 AS CurrentValue
          ,CASE WHEN Column1+1<>ISNULL(LEAD(Column1) OVER(ORDER BY Column1),10000) 
                 AND Column1-1<>ISNULL(LAG(Column1) OVER(ORDER BY Column1),-1) THEN 'gap' ELSE '' END AS MarkGaps
    FROM @tbl AS t
)
SELECT CurrentValue
      ,CASE WHEN CurrentValue-1<>ISNULL(LAG(CurrentValue) OVER(ORDER BY CurrentValue),10000) THEN 'grpStart' ELSE '' END
FROM Neighbours
WHERE MarkGaps = '';

结果

CurrentValue    
10  grpStart
11  
12  
27  grpStart
28  
29  

为了获得计数,您可以计算“grpStart”

© www.soinside.com 2019 - 2024. All rights reserved.