求助:SQL查询,分组,列数据合并问题。
数据示例:
字段1 字段2 字段3
A 1
A 1 001
A 2 006
A 2 003
B 1 007
B 1 005
查询结果要求,根据字段1、字段2分组,字段3的值连接在一起,字段3为空不参与分组连接。
结果入下图:
字段1 字段2 字段3
A 1
A 1 001
A 2 006,003,
B 1 007,005,
[解决办法]
declare @test table(col1 varchar(1),col2 int,col3 varchar(3))insert into @testselect 'A',1,'' union all select 'A',1,'001' union allselect 'A',2,'006' union allselect 'A',2,'003' union allselect 'B',1,'007' union allselect 'B',1,'005'select * from( select t.col1, t.col2, col3=(case when isnull(t.col3,'')<>'' then stuff((select ','+col3 from @test where isnull(col3,'')<>'' and t.col1=col1 and t.col2=col2 for xml path('')),1,1,'') else t.col3 end) from @test t)ttgroup by col1,col2,col3/*col1 col2 col3---- ----------- -------------A 1 A 1 001A 2 006,003B 1 007,005*/
[解决办法]
declare @T table (字段1 varchar(1),字段2 int,字段3 varchar(3))insert into @Tselect 'A',1,null union allselect 'A',1,'001' union allselect 'A',2,'006' union allselect 'A',2,'003' union allselect 'B',1,'007' union allselect 'B',1,'005'select 字段1,字段2,[字段3] from @T where 字段3 is nullunion allselect 字段1,字段2,[字段3]=stuff((select ','+字段3 from @T t where 字段2=a.字段2 and 字段1=a.字段1 for xml path('')), 1, 1, '') from @T a where 字段3 is not nullgroup by 字段1, 字段2/*字段1 字段2 字段3---- ----------- ------------A 1 NULLA 1 001A 2 006,003B 1 007,005*/