简体   繁体   中英

SQL Server - Finding Number patterns

I've been looking at this this for the last hour and just can't seem to find a way to do it, I'm sure its pretty simple but my google and reading skills have failed me.

All I need to do is to find ascending and descending numerical patterns in a field.

Like in this pseudo-SQL Code:

select * where col = '123456' or '23456' or '7654' or '987654321'

Most of the pattern methods using LIKE seem to be around placement of characters/numbers rather than the specific ordering,

I've started trying to create a query than takes the first character and compares it to the next one but this seems really ineffective and inefficient as it would need to take each field in the column run the query and return it if it matches.

I've managed to find a way to get it if its a repeated character but not if its an increase or decrease.

Any help would be greatly appreciated.

You can put regular expression inside your LIKE quotes. Ascending:

^(?=\d{4,10}$)1?2?3?4?5?6?7?8?9?0?$

Descending:

^(?=\d{4,10}$)9?8?7?6?5?4?3?2?1?0?$

d{4,10} here is possible value length, between 4 and 10 symbols.
Won't be fast, most likely.

You can check how it works on http://rubular.com/ .

Edit: Sorry, I forgot to mention you will have to do a MS SQL Server CLR integration first. By default, MSSQL Server does not fully support RegEx.

This article describes how to create and use extensions for the LIKE (Transact-SQL) clause that supports Regular Expressions.

http://www.codeproject.com/Articles/42764/Regular-Expressions-in-MS-SQL-Server

Another option could be something like this:

Declare @Table table (col int)
Insert into @Table values
(4141243),(4290577),(98765432),(78635389),(4141243),(22222),(4290046),(55555555),(4141243),(6789),(77777),(45678),(4294461),(55555),(4141243),(5555)

Declare @Num table (Num int);Insert Into @Num values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)

Select Distinct A.*
  From @Table A
  Join (
        Select Patt=replicate(Num,3) from @Num
        Union All
        Select Patt=right('000'+cast((Num*100+Num*10+Num)+12 as varchar(5)),3) from @Num where Num<8
        Union All
        Select Patt=reverse(right('000'+cast((Num*100+Num*10+Num)+12 as varchar(5)),3)) from @Num where Num<8
       ) B on CharIndex(Patt,cast(col as varchar(25)))>0

Returns

Col
5555
6789
22222
45678
55555
77777
55555555
98765432

**

Think RUMMY 500. A groups or runs of 3. For example 123 or 321 or 333 would be a hit.

**

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM