原表:
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 |
貌似很简单,以我的思考,先写一个聚合函数,然后再查询语句里面调用这个聚合函数;实际上还有更简单的办法,这是作者给出的解决办法,没有用到自定义聚合函数,他用的是FOR XML PATH(‘’)这样的处理方式,感觉真是爽
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
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
如果你还有其他的解决办法,希望你也能给出你的答案, 多多益善