我需要从这样的列表中过滤“ N”个连续的“ X”记录组:
1
4
5
6
9
12
在样本列表中,当X = 2时,连续的“ X”记录组为:
4,5
5,6
有没有一种方法可以使用SQL Server 2008的窗口函数来获得该结果?
答案 0 :(得分:1)
如何?
DECLARE @x int = 2;
WITH
consecutive_groups (n, grp) AS (
SELECT n, n - ROW_NUMBER() OVER (ORDER BY n)
FROM NumbersTable
),
groups_with_minmax (n, grp, nMin, nMax) AS (
SELECT n, grp
, MIN(n) OVER (PARTITION BY grp)
, MAX(n) OVER (PARTITION BY grp)
FROM consecutive_groups
)
SELECT n AS SequenceStart, n+@x-1 AS SequenceEnd
FROM groups_with_minmax
WHERE n+@x-1 BETWEEN nMin AND nMax;
使用的所有窗口函数应在SQL Server 2008中可用。