如何获得数字范围内的最大连续值?

时间:2013-04-30 16:11:45

标签: sql

我在上面的选择中得到了具体的结果:

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个)。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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);
}