查找字符串是否包含数字序列

时间:2018-02-21 05:41:06

标签: sql sql-server

我试图提出一个查询,该查询可以确定字符串(varchar)中是否存在3个或更多数字的数字序列。这适用于SQL Server

示例字符串:" 521324567" 将返回此行数据,因为它具有序列" 4567"。

示例字符串:" 410747823" 不会返回此行数据,因为没有3个或更多数字的序列。

示例字符串:" 1274563619" 将返回此行数据,因为它具有序列" 456"。

我想如果它是一个固定长度的字符串,我可能会想到类似于下面的sql的东西。

Select num from numbers where substring(num,2,1)=
(select substring(num,1,1)) + 1

3 个答案:

答案 0 :(得分:4)

只有7种可能的序列,所以:

time.sleep(4)
rawpage=driver.page_source #storing the webpage in variable
souppage=BeautifulSoup(rawpage,"html.parser") #parsing the webpage
tbody=souppage.find("table",{"id":"table_devicesensortable"}) #scrapping

如果算上select num from numbers where num like '%123%' or num like '%234%' or num like '%345%' or num like '%456%' or num like '%567%' or num like '%678%' or num like '%789%' ,那么你也可以为此添加一个条件。

答案 1 :(得分:1)

试试这个。我知道这有点复杂。但是Works动态

DECLARE @MyNum NVARCHAR(50) = '1274563619'

;WITH CTE
AS
(
    SELECT
       SeqNo = 1,
       MyNum = @MyNum,
       PosNum = SUBSTRING(@MyNum,1,1)
    UNION ALL
    SELECT
       SeqNo = SeqNo +1,
       MyNum,
       PosNum = SUBSTRING(MyNum,SeqNo,1)
       FROM CTE
          WHERE SeqNo <= LEN(@MyNum)
)
SELECT
    MyNum
    FROM CTE C1
       WHERE EXISTS
       (
          SELECT 1 FROM CTE C2
             WHERE 
                (
                    C2.SeqNo = C1.SeqNo+1 
                    AND
                    C2.PosNum = C1.PosNum+1
                )
                OR
                (
                    C2.SeqNo = C1.SeqNo+2 
                    AND
                    C2.PosNum = C1.PosNum+2
                )
       )
       GROUP BY MyNum
          HAVING COUNT(1)>2

答案 2 :(得分:0)

波希米亚语是正确的,但这里是选择列表的变体:

select num, case when 
   num like '%012%'
   or num like '%123%'
   or num like '%234%'
   or num like '%345%'
   or num like '%456%'
   or num like '%567%'
   or num like '%678%'
   or num like '%789%'
   or num like '%890%'
   or num like '%901%' 
then 'Yep' else 'Nope' end as is_there_a_sequence
from numbers

我还添加了012890。虽然901可能是一座过头的桥梁。

我希望这会有所帮助。