首页 > 代码库 > SQL 分组后拼接字符串

SQL 分组后拼接字符串

with t  as(select Charles parent, William child unionselect Charles, Harry unionselect Anne, Peter unionselect Anne, Zara unionselect Andrew, Beatrice unionselect Andrew, Eugenie )SELECT parent, STUFF(     (       SELECT ,+ child FROM t a WHERE b.parent = a.parent FOR XML PATH(‘‘)     ),1 ,1, ‘‘) children FROM t b GROUP BY parent

 

原表:

Parent
Child
CharlesWilliam
CharlesHarry
AnnePeter
AnneZara
AndrewBeatrice
AndrewEugenie

 

处理的结果: 

Parent
Children
CharlesWilliam,Harry
AnnePeter,Zara
AndrewEugenie,Beatrice