0

I have a table in the following format:

 cId    seq 
 ---    --- 
 A      1
 A      2
 A      4
 A      5
 B      8
 B      9
 A      12
 A      13

I would like to write a query that would produce another table that looks like:

 cId    seq    consecutive
 ---    ---    -----------
 A      1      1
 A      2      1
 A      4      2
 A      5      2
 B      8      3
 B      9      3
 A      12     4
 A      13     4

What I am trying to do is identify consecutive seq values that have the same cId and then number them.

I was thinking of using Lag function to determine the previous seq value and then setting the consecutive column but don't know how to increment the value when I encounter the next break.

SELECT [cId], 
       [Seq],
       CASE WHEN [Seq] - 1 = LAG([Seq], 1, [Seq]) OVER ( ORDER BY [Seq])  THEN 1 
       ELSE 2 END as consecutive
FROM #ConsecutiveData

This query will put a 2 next to the start of each sequence. That's the closest I have come.

4

1 回答 1

3

我认为作者没有使用 MySQL,因为据我所知,LAGMySQL 中没有任何功能。

下面是一个可能的 MSSQL 解决方案:

SELECT
    cid,
    seq,
    DENSE_RANK() OVER (ORDER BY seq - row_num) consecutive
  FROM (
    SELECT
        cid,
        seq,
        ROW_NUMBER() OVER (ORDER BY seq) row_num
      FROM
        test_table
  ) data
;

在 SQLFiddle 检查:SQLFiddle Example

于 2013-11-06T23:44:33.250 回答