日期:2014-05-16 浏览次数:20549 次
create table test_a
(
code VARCHAR(10),
remark VARCHAR(10)
)
insert into test_a
select 'A','1' UNION
select 'A','2' UNION
select 'A','3' UNION
select 'B','11' UNION
select 'B','22' UNION
select 'C','33'
求算法要求按code分组合并remark字段,转换后为:
code remark
A 1,2,3
B 11,22
C 33
希望也能给出逆向的算法
create table test_a
(
code VARCHAR(10),
remark VARCHAR(10)
)
insert into test_a
select 'A','1' UNION
select 'A','2' UNION
select 'A','3' UNION
select 'B','11' UNION
select 'B','22' UNION
select 'C','33'
--code remark
--A 1,2,3
--B 11,22
--C 33
--执行查询
select code ,stuff((SELECT ',' + b.remark FROM test_a AS b WHERE b.code = a.code FOR XML PATH('')) ,1,1,'') FROM test_a AS a GROUP BY code
--执行结果
---------- -----------------
A 1,2,3
B 11,22
C 33
(3 行受影响)
--创建函数
create function f_splitstr(@SourceSql varchar(8000),@StrSeprate varchar(100))
returns @temp table(F1 varchar(100))
as
begin
declare @ch as varchar(100)
set @SourceSql=@SourceSql+@StrSeprate
while(@SourceSql<>'')
begin
set @ch=left(@SourceSql,charindex(',',@SourceSql,1)-1)
insert @temp values(@ch)
set @SourceSql=stuff(@SourceSql,1,charindex(',',@SourceSql,1),'')
end
return
end
--借助上一个查询的结果
;WITH acte AS (
select code ,stuff((SELECT ',' + b.remark FROM test_a AS b WHERE b.code = a.code FOR XML PATH('')) ,1,1,'') AS remark FROM test_a AS a GROUP BY code)
--执行
SELECT b.f1 , acte.* FROM acte cross apply f_splitstr(acte.remark , ',') AS b
--执行结果
f1 code