SQL Count按一系列数字分组

时间:2013-02-07 15:43:52

标签: sql sql-server group-by sequence gaps-and-islands

我有一个这样的SQL表:

id      pNum
-----   --------
100     12
100     13
100     15
100     16
100     17
200     18
200     19
300     20
300     21
300     25

我希望按id和pNum序列进行分组,并计算行数。得到这样的结果。

id      res
-----   --------
100     2
100     3
200     2
300     2
300     1

关于如何做的任何想法?

2 个答案:

答案 0 :(得分:4)

如果您的DBMS支持窗口功能(例如SQL Server 2005 +)

SELECT id,
       count(*) AS res
FROM   (SELECT *,
               [pNum] - ROW_NUMBER() OVER (PARTITION BY [id] ORDER BY [pNum]) AS Grp
        FROM   YourTable) T
GROUP  BY id,
          Grp 

SQL Fiddle

答案 1 :(得分:2)

使用this question中的解决方案:

declare @table table
(
    id int
    , pnum int
)


insert into @table
values (100,    12)
, (100,     13)
, (100,     15)
, (100,     16)
, (100,     17)
, (200,     18)
, (200,     19)
, (300,     20)
, (300,     21)
, (300,     25)

;WITH numbered AS (
  SELECT
    ID, pnum,
    SeqGroup = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY pnum) - pnum
  FROM @table
)
SELECT
  ID,
  COUNT(*) AS res
FROM numbered
GROUP BY ID, SeqGroup
ORDER BY id, MIN(pnum)