2017-05-18 83 views
0

好的 - 所以我搜索了這個網絡,沒有一個我發現的例子和我的一模一樣。找到連續的數字

我有一個5列和數千行的表。 我需要在每行中找到連續的數字。我需要使用以下

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) 

這就是我要的列移動到行3次所示的查詢的情況下結束了,但我不知道現在該怎麼檢查。

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 

幫助:-)!

+2

在一般情況下,這看起來像一個空白和孤島問題,除了你的數據格式使得數據庫在幫助中毫無用處。您一定要獲取存儲在列中的每個序列的數據,而不是跨行中的列。 –

+0

感謝您的回覆。這也是我的想法,這就是查詢發佈的內容。它將爲每行創建一個具有1列的新臨時表。結果是具有不同行中的數字的一列。 – Gunnar

+0

你能告訴我們你正在使用哪個數據庫嗎?不同平臺之間的SQL有不同的變化,可能有助於這種情況。 – Nathan

回答

0

好的,我明白了。對於上述行,這個查詢返回值爲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 
+0

hmm,所以這對1條記錄非常有用(在這種情況下,ID爲8的行)。但是,如何更改此查詢以爲每行返回1個結果? – Gunnar

+0

任何任何想法? – Gunnar