数据表tb:
ID TName List
1 T1 1
2 T2 1,2
3 T3 1,2,3
4 T4 1,2,4
我想取出所有List字段里,数字"2" 排在第二位的数据(像1,2,3这个数据,2就是排在第二位,如果是1,3,2 这个2就排在第三位这样的).得出结果:
2 T2 1,2
3 T3 1,2,3
4 T4 1,2,4
同理,如果我想取得List字段里,数字"4"排在第三位的所有数据,得出结果:
4 T4 1,2,4
如何写Sql语句? 非常感谢!
------解决思路----------------------
create table tb
(ID int,TName varchar(10),List varchar(20))
insert into tb
select 1,'T1','1' union all
select 2,'T2','1,2' union all
select 3,'T3','1,2,3' union all
select 4,'T4','1,2,4'
-- 创建函数
create function dbo.fn_tb
(@list varchar(20),
@i int)
returns int
as
begin
declare @y int
select @y=(select y
from (select row_number() over(order by getdate()) 'rn',
substring(a.s,b.number,charindex(',',a.s+',',b.number)-b.number) 'y'
from (select @list 's') a,master.dbo.spt_values b
where b.type='P' and b.number between 1 and len(a.s)
and substring(','+a.s,b.number,1)=',') t
where rn=@i)
return @y
end
-- 数字"2"排在第二位的数据
select *
from tb
where dbo.fn_tb(List,2)=2
/*
ID TName List
----------- ---------- --------------------
2 T2 1,2
3 T3 1,2,3
4 T4 1,2,4
(3 row(s) affected)
*/
-- 数字"4"排在第三位的所有数据
select *
from tb
where dbo.fn_tb(List,3)=4
/*
ID TName List
----------- ---------- --------------------
4 T4 1,2,4
(1 row(s) affected)
*/