列合并与拆分

----------------------列拆分和合并---------------------
declare @tb table (id int,value varchar(30))
insert into @tb select 1,'a,bb'
     union all  select 2,'a,bb,ccc,dddd'
---方法1:
--select id,value=substring(value,number,charindex(',',value+',',number)-number) from @tb a ,master..spt_values b
--       where substring(','+value,number,1)=',' and type='p'
---方法2:
select a.id,b.va from
(select id,value=convert(xml,'<root><v>'+replace(value,',','</v><v>')+'</v></root>') from @tb) a
outer apply
(select va= n.v.value('(.)','varchar(100)') from A.value.nodes('root/v') n(v)) b
go
----合并方法1
if object_id('tb') is not null
   drop table tb
if object_id('c_f') is not null
   drop function c_f
go
create table tb (id int,value varchar(30))
insert into tb select 1,'a'
     union all  select 1,'bb'
     union all  select 2,'a'
     union all  select 2,'bb'
     union all  select 2,'ccc'
     union all  select 2,'dddd'
go
create function c_f(@id int)
returns nvarchar(100)
as
begin
declare @value nvarchar(100)
set @value='';
select @value=@value+','+ value from tb where id=@id
set @value=stuff(@value,1,1,'')
return @value
end
go
select id,dbo.c_f(id) from tb group by id
---方法2
select id ,value=stuff((select ','+value from tb where a.id=id for xml path('')),1,1,'')
from tb a group by id
---方法3
select * from
  (select distinct id from tb) a
  outer apply
  (select d=stuff(replace(replace((select value from tb where a.id=id for xml auto),
         '<tb value="',','),'"/>',''),1,1,'')) b 

 

 

 

----------结果

 

 


(2 行受影响)
id          va
----------- ----------------------------------------------------------------------------------------------------
1           a
1           bb
2           a
2           bb
2           ccc
2           dddd

(6 行受影响)


(6 行受影响)
id         
----------- ----------------------------------------------------------------------------------------------------
1           a,bb
2           a,bb,ccc,dddd

(2 行受影响)

id          value
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1           a,bb
2           a,bb,ccc,dddd

(2 行受影响)

id          d
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1           a,bb
2           a,bb,ccc,dddd

(2 行受影响)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值