select stuff((select ','+w.Waybillno from Web_Way_Waybill w where w.IsValid<>'Y' AND w.TruckOrder='T1712220007' FOR XML PATH('')),1,1,''))+ left(',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,',
(59- (select len(( select stuff((select ','+w.Waybillno from Web_Way_Waybill w
where w.IsValid<>'Y' AND w.TruckOrder='T1712220007' FOR XML PATH('')),1,1,'')) )-len(replace(
(select stuff((select ','+w.Waybillno from Web_Way_Waybill w where w.IsValid<>'Y' AND w.TruckOrder='T1712220007' FOR XML PATH('')),1,1,'')) ,',','')))))
as Waybillnostr,
insert into @T1 (UserID,UserName,CityName) values (1,'a','上海')
insert into @T1 (UserID,UserName,CityName) values (2,'b','北京')
insert into @T1 (UserID,UserName,CityName) values (3,'c','上海')
insert into @T1 (UserID,UserName,CityName) values (4,'d','北京')
insert into @T1 (UserID,UserName,CityName) values (5,'e','上海')
select * from @T1
-----最优的方式
SELECT CityName,STUFF((SELECT ',' + UserName FROM @T1 subTitle WHERE CityName=A.CityName FOR XML PATH('')),1, 1, '') AS A
FROM @T1 A
GROUP BY CityName