日期:2014-05-17  浏览次数:20453 次

求助: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,



------解决方案--------------------
SQL code


declare @test table(col1 varchar(1),col2 int,col3 varchar(3))
insert into @test
select 'A',1,'' union all   
select 'A',1,'001' union all
select 'A',2,'006' union all
select 'A',2,'003' union all
select 'B',1,'007' union all
select '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
)tt
group by col1,col2,col3
/*
col1 col2        col3
---- ----------- -------------
A    1           
A    1           001
A    2           006,003
B    1           007,005
*/

------解决方案--------------------
SQL code

declare @T table (字段1 varchar(1),字段2 int,字段3 varchar(3))
insert into @T
select 'A',1,null union all
select 'A',1,'001' union all
select 'A',2,'006' union all
select 'A',2,'003' union all
select 'B',1,'007' union all
select 'B',1,'005'

select 
    字段1,字段2,[字段3] 
from @T where 字段3 is null
union all
select 
    字段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 null
group by 字段1, 字段2

/*
字段1  字段2         字段3
---- ----------- ------------
A    1           NULL
A    1           001
A    2           006,003
B    1           007,005
*/