你可以使用下面的
步骤说明
- 将数字分成几行
- 对行求和
- 再次对数字进行分组
示例设置
declare @data table(
Id int not null identity(1,1),
Numbers nvarchar(max) not null
)
insert into @data(Numbers)
values('1,0,0,1,0,2,1,0,0,1,0,1'),
('1,0,0,2,0,0,1,0,0,1,0,1'),
('1,0,0,1,1,0,1,0,0,1,0,1'),
('1,0,0,1,0,5,1,0,0,1,0,1')
查询
;with Split as
(
select
Id,1 as Number,left(Numbers,charindex(',',Numbers)-1) as Part
,right(Numbers,len(Numbers)-charindex(',',Numbers)) as Rest
from @data
where Numbers is not null and charindex(',',Numbers)>0
union all
select
Id, Number +1,left(Rest,charindex(',',Rest)-1)
,right(Rest,len(Rest)-charindex(',',Rest))
from Split
where Rest is not null and charindex(',',Rest)>0
union all
select
Id,Number+1,Rest,null
from Split
where Rest is not null and charindex(',',Rest)=0
),sumRows as(
select Number ,sum(cast(Part as int)) as Total
from Split
group by Number
), groupValues as (
select Id,stuff((
select ',' + cast(r.Total as varchar)
from sumRows r
inner join Split s on s.Number = r.Number
where (s.Id =d.Id )
for xml path(''),type).value('(./text())[1]','varchar(max)')
,1,1,'') as Numbers
from @data d
)
select * from groupValues
结果
Id Numbers
1 4,0,0,5,1,7,4,0,0,4,0,4
2 4,0,0,5,1,7,4,0,0,4,0,4
3 4,0,0,5,1,7,4,0,0,4,0,4
4 4,0,0,5,1,7,4,0,0,4,0,4
希望对你有帮助