这是我的数据,每个ThroughRouteSid
记录都有相同的模式。
六个数字和五个逗号。然后我只想得到三和五
将数字分成两个记录到模板表并得到相同的Count()
值这两个记录。
例如:图片中的第一条记录。
ThroughRouteSid(3730,2428,2428,3935,3935,3938,) Count(32)
。
我想要一个这样的结果:
2428 32 3935 32
我得到了我想要的数字。成为两条记录,并且两者都有相同的Count值进入模板表
答案 0 :(得分:0)
您可以使用XML来获取结果,请参阅下面的示例代码 -
create table #t1( ThroughRouteSid varchar(500) , Cnt int)
insert into #t1
select '3730,2428,2428,3935,3935,3938,' , len('3730,2428,2428,3935,3935,3938,')
union all select '1111,2222,3333,4444,5555,6666,' , len('1111,2222,3333,4444,5555,6666,')
select cast( '<xml><td>' + REPLACE( SUBSTRING(ThroughRouteSid ,1 , len(ThroughRouteSid)-1),',','</td><td>') + '</td></xml>' as xml) XmlData , Cnt
into #t2 from #t1
select XmlData.value('(xml/td)[3]' ,'int' ), Cnt ,XmlData.value('(xml/td)[5]' ,'int' ), Cnt
from #t2
答案 1 :(得分:0)
首先创建引用How to Split a string by delimited char in SQL Server的函数。然后尝试查询以下内容
select (SELECT CONVERT(varchar,splitdata) + ' '+ Convert(varchar, [Count])+' ' FROM (select splitdata, ROW_NUMBER() over (ORDER BY (SELECT 100)) row_no
from [dbo].[fnSplitString](ThroughRouteSid,',')
where splitdata != '') as temp where row_no in (2,5)
for xml path('')) as col1 from [yourtable]
答案 2 :(得分:0)
如果您使用的是SQL Server 2016,则可以执行以下操作:
create table #temp (ThroughRouteSid varchar(1024),[Count] int)
insert into #temp values
('3730,2428,2428,3935,3935,3938,',32),
('730,428,428,335,935,938,',28)
select
spt.value,
t.[Count]
from #temp t
cross apply (
select value from STRING_SPLIT(t.ThroughRouteSid,',') where LEN(value) > 0
)spt