有个表如下:
if exists(select top(1)1 from sys.objects with(nolock) where name=N'tb' and type=N'U')
drop table tb
create table tb(sname varchar(10),hobby varchar(10))
insert into tb(sname,hobby)
select N'张三',N'游泳' union all
select N'张三',N'游泳' union all
select N'李四',N'爬山' union all
select N'李四',N'跑步'
--想显示如下:
--sname hobby hobby2
--张三 游泳,游泳 游泳
--李四 爬山,跑步 爬山,跑步
--我现在只会实现第一列,第二列hobby2中要把重复的给去掉,不知道怎么搞。第一列的实现方式
select sname
,hobby=(stuff((select ','+hobby from tb where sname=a.sname for xml path('')),1,1,''))
from tb a group by sname
--帮我实现第二列,谢谢
------解决方案--------------------
select sname
,hobby=(stuff((select ','+ hobby from tb where sname=a.sname GROUP BY hobby for xml path('')),1,1,''))
from tb a group by sname
------解决方案--------------------
加distinct不就可以了
select sname,hobby=(stuff((select ','+hobby from tb where sname=a.sname for xml path('')),1,1,'')),
hobby2=(stuff((select distinct ','+hobby from tb where sname=a.sname for xml path('')),1,1,''))
from tb a group by sname
------解决方案--------------------
加 DISTINCT
DISTINCT ','+hobby