首页 > 代码库 > 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 |
Charles | William |
Charles | Harry |
Anne | Peter |
Anne | Zara |
Andrew | Beatrice |
Andrew | Eugenie |
处理后的结果:
Parent | Children |
Charles | William,Harry |
Anne | Peter,Zara |
Andrew | Eugenie,Beatrice |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。