我有一个包含5列和数千行的表。 我需要在每一行中找到连续的数字。我需要针对下面显示的情况进行3次查询
n1 n2 n3 n4 n5
=======================
1 3 4 6 9 = should result in 1 (when checking for pairs)
1 3 4 5 9 = should result in 1 (when checking for triplets)
1 2 5 8 9 = should result in 1 (when checking for double pairs)
这就是我必须将列移动到行中,但我不知道如何检查这些。
select n1 from (
select n1 from myTable where Id = 1
union all select n2 from myTable where Id = 1
union all select n3 from myTable where Id = 1
union all select n4 from myTable where Id = 1
union all select n5 from myTable where Id = 1
) t
order by n1
感谢您的帮助!
@TimBiegeleise,更新: 所以我在Google上找到了Gaps&岛屿:
SELECT ID, StartSeqNo=MIN(SeqNo), EndSeqNo=MAX(SeqNo)
FROM (
SELECT ID, SeqNo
,rn=SeqNo-ROW_NUMBER() OVER (PARTITION BY ID ORDER BY SeqNo)
FROM dbo.GapsIslands) a
GROUP BY ID, rn;
这是我更新的查询将列转换为行(但它需要2个语句,我更确切地说有1个)并实现岛部分 - 但我不明白如何给我结果我需要的(见上文)。下面我显示原始行数据和结果。
select n1, IDENTITY (INT, 1, 1) AS ID
into #test
from (
select n1 from myTable where Id = 8
union all select n2 from myTable where Id = 8
union all select n3 from myTable where Id = 8
union all select n4 from myTable where Id = 8
union all select n5 from myTable where Id = 8
) as t
order by n1
SELECT ID, StartSeqNo=MIN(n1), EndSeqNo=MAX(n1)
FROM (
SELECT ID, n1
,rn=n1-ROW_NUMBER() OVER (PARTITION BY ID ORDER BY n1)
FROM #test) a
GROUP BY ID, rn
drop table #test
original row - should return 1 (when checking for "pair"/consecutive numbers
n1 n2 n3 n4 n5
=======================
31 27 28 36 12
我得到上述查询的结果:
StartSeqNo EndSeqNo
1 12 12
2 27 27
3 28 28
4 31 31
5 36 36
帮助:-)!
答案 0 :(得分:0)
select COUNT(*) as pairs
from (
SELECT StartSeqNo=MIN(n1), EndSeqNo=MAX(n1)
FROM (
SELECT n1, rn=n1-ROW_NUMBER() OVER (ORDER BY n1)
from (
select n1 from myTable where Id = 8
union all select n2 from myTable where Id = 8
union all select n3 from myTable where Id = 8
union all select n4 from myTable where Id = 8
union all select n5 from myTable where Id = 8
) t
) x
GROUP BY rn
) z
where StartSeqNo+1 = EndSeqNo