读书人

SQL 依据规律查找数据

发布时间: 2012-12-18 12:43:41 作者: rapoo

SQL 根据规律查找数据
用户设置了一个顺序 234
2必须为数据的开头。
如果数据片段符合下面几种情况,则返回true.
2,1,2,3,1,2,4 (234之间隔2位)
2,1,2,3,3,1,2,3,4 (234之间隔3位)
2,1,2,3,4,3,1,2,3,4,4 (234之间隔4位)
2,1,2,3,4,5,3,1,2,3,4,5,4 (234之间隔5位)

那么 如果数据为
2,1,1,1,1,1,3,1,1,1,1,1,4,1,1,1,1,1,1,1,
怎么写SQL,判断234 是否在上面4种情况





[最优解释]

declare @str varchar(20)='2,1,2,3,1,2,4'
declare @return int=0
select @return=1
from (select @str as f ) as a
where f like '%2_____3_____4%'
or f like '%2_______3_______4%'
or f like '%2_________3_________4%'
or f like '%2___________3___________4%'

select @return

[其他解释]
where like '2__3__4'
[其他解释]
间隔没关系:like '2%3%4%'
有关系:like '2_3_4%'
[其他解释]


select * from a where a like'%2%3%4%'

[其他解释]
数据没这么简单吧,给出你的真实数据。
[其他解释]
引用:
数据没这么简单吧,给出你的真实数据。

数据是这样的。
1,2,8,6,2,7,3,9,2,5,7,5,4,5,8,2,2,1,5,4,5,7,3,9,0,1,2,5,6

首先在这组数据开头添加内容为2的数据,
2,1,2,8,6,2,7,3,9,2,5,7,5,4,5,8,2,2,1,5,4,5,7,3,9,0,1,2,5,6
然后判断已2开头,并且是否符合234上面四种规律。每个值都是0-9之间的数。

[其他解释]
select col
from tb,master..spt_values b
where
b.type='P'
and LEFT(col,1)='2'
and SUBSTRING(tb,1+number,1)='3'
and SUBSTRING(tb,1+2*number,1)='4'

[其他解释]
select col
from tb,master..spt_values b
where
b.type='P'
and LEFT(col,1)='2'
and SUBSTRING(col,1+number,1)='3'
and SUBSTRING(col,1+2*number,1)='4'

[其他解释]
引用:
SQL code12345678910declare @str varchar(20)='2,1,2,3,1,2,4'declare @return int=0select @return=1from (select @str as f ) as a where f like '%2_____3_____4%' or f like '%2_______3_______4%……


非常感谢,如果用户要求 234之间能隔1-9位这9九情况,这样要写很多or f like
SQL 能不能优化
[其他解释]
where charindex(字段,'2')=1
and 2*charindex(字段,'3')-charindex(字段,'4')=1
[其他解释]
引用:
引用:SQL code12345678910declare @str varchar(20)='2,1,2,3,1,2,4'declare @return int=0select @return=1from (select @str as f ) as a where f like '%2_____3_____4%' or f like ……


应该可以再优化 ,坐等高人

读书人网 >SQL Server

热点推荐