--按字段分组,将该组下某个字段多行以逗号拼接成一行
CREATE TABLE t1 ( mid INT, uid VARCHAR(1) )
insert into t1 values (1,'a')
insert into t1 values (1,'b')
insert into t1 values (1,'b')
insert into t1 values (1,'c')
insert into t1 values (1,'d')
insert into t1 values (2,'a')
insert into t1 values (2,'b')
insert into t1 values (2,'c')
insert into t1 values (2,'c')
insert into t1 values (3,'a')
insert into t1 values (3,'b')
insert into t1 values (3,'c')
insert into t1 values (3,'c')
select mid,stuff((select distinct ','+uid from t1 where a.mid=mid for xml path('')),1,1,'') AS items
from t1 a group by mid
--结果
mid items
1 a,b,c,d
2 a,b,c
3 a,b,c