[英]finding consecutive numbers
好的-所以我在互聯網上搜索了此內容,但我發現的所有示例都與我的完全不同。
我有一個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,更新:所以我在谷歌上找到了關於差距和島嶼的信息:
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
救命 :-) !
好,我知道了。 該查詢為上述行返回值1
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.