create table aa
(
UserID int ,
UserName nvarchar(50),
CityName nvarchar(50)
);
insert into aa (UserID,UserName,CityName) values (1,'a','上海')
insert into aa (UserID,UserName,CityName) values (2,'b','北京')
insert into aa (UserID,UserName,CityName) values (3,'c','上海')
insert into aa (UserID,UserName,CityName) values (4,'d','北京')
insert into aa (UserID,UserName,CityName) values (5,'e','上海')
select * from aa
sqlserver
SELECT CityName,STUFF((SELECT ',' + UserName FROM aa subTitle WHERE CityName=A.CityName FOR XML PATH('')),1, 1, '') AS A
FROM aa A
GROUP BY CityName
oracle:
SELECT CityName,LISTAGG(UserName, ',') WITHIN GROUP(ORDER BY UserName) AS usernames
FROM aa GROUP BY CityName;