日期:2014-05-18  浏览次数:20692 次

SQL大师来,问个查询语句
表结构和内容如下
Name--Age--NO--Remark
A--11--11--ABC
A--11--11--CCC
A--11--11--AAA
B--11--11--CCC
B--11--11--DDD
=======================================================
查询后的结果为
Name--Age--NO--Remark
A--11--11--ABC,CCC,CCC
B--11--11--CCC,DDD

就是前面三列数据重复的合并,后面一列不同的串起来。
重复的可能是2行,3行,或是更多行,求解。
补充一句,最后一列Remark会有NULL值,和前面是同样的处理方式,前三列合并,后面的就不用串起来了,还是写NUll

------解决方案--------------------
SQL code
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([Name] varchar(1),[Age] int,[NO] int,[Remark] varchar(3))
insert [tb]
select 'A',11,11,'ABC' union all
select 'A',11,11,'CCC' union all
select 'A',11,11,'AAA' union all
select 'B',11,11,'CCC' union all
select 'B',11,11,'DDD' union all
select 'A',11,11,NULL
go

select name,age,no,
  remark=stuff((select ','+remark from tb where remark is not null and name=t.name and age=t.age and no=t.no for xml path('')),1,1,'')
from tb t
where remark is not null
group by name,age,no
UNION ALL
SELECT * FROM TB WHERE REMARK IS NULL

/**
name age         no          remark
---- ----------- ----------- -----------------------
A    11          11          ABC,CCC,AAA
B    11          11          CCC,DDD
A    11          11          NULL

(3 行受影响)
**/