数据库记录中的字符串相加问题
表a:
name address
张三 北京
李四 河北
王五 河南
张三 朝阳区
张三 阳光大街
李四 沧州
........
怎么按姓名将address合并,并形成一张新表
------解决方案--------------------
- SQL code
--> 测试数据:[tbl]if object_id('[tbl]') is not null drop table [tbl]create table [tbl]([name] varchar(4),[address] varchar(8))insert [tbl]select '张三','北京' union allselect '李四','河北' union allselect '王五','河南' union allselect '张三','朝阳区' union allselect '张三','阳光大街' union allselect '李四','沧州'select * into #tt from(SELECT *FROM (SELECT DISTINCT [name] FROM [tbl])AOUTER APPLY( SELECT [address]= STUFF(REPLACE(REPLACE( ( SELECT [address] FROM [tbl] N WHERE [name] = A.[name] FOR XML AUTO ), '<N address="', ' '), '"/>', ''), 1, 1, ''))N)aselect * from #tt/*name address李四 河北 沧州王五 河南张三 北京 朝阳区 阳光大街*/