SQL 分组后拼接字符串
with t as( select ‘Charles‘ parent, ‘William‘ child union select ‘Charles‘, ‘Harry‘ union select ‘Anne‘, ‘Peter‘ union select ‘Anne‘, ‘Zara‘ union select ‘Andrew‘, ‘Beatrice‘ union select ‘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 |
Charles | William |
Charles | Harry |
Anne | Peter |
Anne | Zara |
Andrew | Beatrice |
Andrew | Eugenie |
处理后的结果:
Parent |
Children |
Charles | William,Harry |
Anne | Peter,Zara |
Andrew | Eugenie,Beatrice |
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。