sql2005中一个xml聚合的例子

该问题来自论坛提问,演示SQL代码如下

  1. --建立测试环境
  2. set nocount on
  3. create table test(ID varchar(20),NAME varchar(20))
  4. insert into test select '1','aaa'
  5. insert into test select '1','bbb'
  6. insert into test select '1','ccc'
  7. insert into test select '2','ddd'
  8. insert into test select '2','eee'
  9. go
  10. --测试
  11. select  *from (select  distinct id from test)a
  12. OUTER APPLY(
  13. select value='<root>'+(
  14. select name from test path
  15.                 where id = A.id
  16.                 for xml auto)+'<root/>') b
  17. --删除测试环境
  18. drop table test
  19.  set nocount off
  20. /*--结果
  21. id                   value
  22. -------------------- --------------------------------------------------------------------
  23. 1                    <root><path name="aaa"/><path name="bbb"/><path name="ccc"/><root/>
  24. 2                    <root><path name="ddd"/><path name="eee"/><root/>
  25. */

原文地址:https://www.cnblogs.com/cl1024cl/p/6204881.html