2

我在选择中有上面的具体结果:

1   2
1   3
1   5
1   6
1   9
1   10
1   11
1   13
1   14
1   16
1   18
1   20
1   23
1   24
1   25

我想找到的是结果中出现的最长的加一链。

例如,我知道 3 是这个数字范围内的最大长度序列,来自最后 3 个结果(23、24、25 是连续 3 个)。

4

3 回答 3

5

序列将具有数字和顺序排序之间的差异将是恒定的属性。在大多数 SQL 方言中,您都有一个名为 的函数row_number(),它分配序号。

我们可以使用此观察来解决您的问题:

select (num - seqnum), count(*) as NumInSequence
from (select t.*, row_number() over (order by num) as seqnum
      from t
     ) t
group by (num - seqnum)

这给出了每个序列。要获得最大值,请使用max()子查询或某些版本的limit/ top。例如,在 SQL Server 中,您可以执行以下操作:

select top 1 count(*) as NumInSequence
from (select t.*, row_number() over (order by num) as seqnum
      from t
     ) t
group by (num - seqnum)
order by NumInSQuence desc
于 2013-04-30T16:19:16.537 回答
1

使用这篇文章作为主要查询: http ://www.xaprb.com/blog/2006/03/22/find-contiguous-ranges-with-sql/

只需添加一个计算差异的列并选择 MAX()。

SELECT MAX(seq.end - seq.start)
FROM (
select l.id as start,
    (
        select min(a.id) as id
        from sequence as a
            left outer join sequence as b on a.id = b.id - 1
        where b.id is null
            and a.id >= l.id
    ) as end,
from sequence as l
    left outer join sequence as r on r.id = l.id - 1
where r.id is null;
) AS seq
于 2013-04-30T16:20:31.063 回答
0

@Gordon 给出了一个绝妙且更简洁的答案。但是,我认为递归实现也可能有用。这是一篇关于递归 CTE 的非常有用的文章:http: //msdn.microsoft.com/en-us/library/ms186243 (v=sql.105).aspx

-- This first CTE is unnecessary because you presumably already have 
-- your data.  But I wanted to include it to make it easier test.
WITH myNumbers AS (
SELECT *
FROM (
        VALUES
        (2),
        (3),
        (5),
        (6),
        (9),
        (10),
        (11),
        (13),
        (14),
        (16),
        (18),
        (20),
        (23),
        (24),
        (25)
    ) AS x (num)
),
-- To get my sequences I recurse until there is no num + 1 in my set
mySequences AS (
    -- Anchor member definition: Create the first invocation
    SELECT v.num, 0 AS iteration, v.num AS previous, v.num AS start
    FROM myNumbers v
    UNION ALL
    -- Recursive member definition: Recurse until value + 1 does not exist
    SELECT s.num + 1, s.iteration + 1 AS iteration, s.num AS previous, s.start
    FROM mySequences s  -- Notice that we can reference the CTE within itself
    JOIN myNumbers v
        ON v.num = s.num + 1
)
-- I must increment by 1 because I chose to start my recursion at 0
SELECT MAX(iteration + 1)
FROM mySequences

那个递归查询类似于写

public int GetSequenceLength(int start, int iteration, int[] myNumbers)
{
    if (myNumbers.Contains(start + 1))
    {
        return GetSequenceLength(start + 1, iteration + 1, myNumbers);
    }
    return iteration;
}
foreach (var myNumber in myNumbers)
{
    var sequenceLength = GetSequenceLength(myNumber, 0, myNumbers) + 1;
    Console.WriteLine(myNumber + " : " + sequenceLength);
}
于 2013-04-30T17:58:28.037 回答