CREATE TABLE TEST6 ( NAME VARCHAR(200), ENTRY_DATE DATE, COMPANY VARCHAR(200) ) INSERT INTO TEST6 VALUES(‘王强‘,‘2008-1-1‘,‘电信‘); INSERT INTO TEST6 VALUES(‘王强‘,‘2009-1-1‘,‘移动‘); INSERT INTO TEST6 VALUES(‘王强‘,‘2010-1-1‘,‘联通‘); INSERT INTO TEST6 VALUES(‘李四‘,‘2008-1-1‘,‘电网‘); INSERT INTO TEST6 VALUES(‘李四‘,‘2009-1-1‘,‘财政局‘); INSERT INTO TEST6 VALUES(‘张三‘,‘2012-12-1‘,‘腾讯‘); INSERT INTO TEST6 VALUES(‘张三‘,‘2013-12-1‘,‘阿里‘); INSERT INTO TEST6 VALUES(‘张三‘,‘2014-12-1‘,‘美团‘); INSERT INTO TEST6 VALUES(‘张三‘,‘2015-12-1‘,‘饿了么‘);
测试表结构如上:
现在需要知道每个员工的任职次序
此时就用到了 FOR XML PATH函数
select COMPANY from TEST6 where NAME = ‘王强‘ for xml path(‘‘)
查询结果:
如果在path中给个参数
select COMPANY from TEST6 where NAME = ‘王强‘ for xml path(‘node‘)
查询结果:
可以看出,原来的节点增加了Node的标签
select COMPANY as myCom from TEST6 where NAME = ‘王强‘ for xml path(‘node‘)
可以看出子节点的标签名也被改了
那如果不想要xml格式的,也可以用以下方法代替
SELECT ‘[ ‘+ COMPANY +‘ ]‘ FROM TEST6 where NAME = ‘王强‘ FOR XML PATH(‘‘)
查询结果如下:
最后拿出我们需要的结果
SELECT B.Name,LEFT(StuList,LEN(StuList)-1) as hobby FROM ( SELECT Name, (SELECT COMPANY+‘,‘ FROM TEST6 WHERE Name=A.Name FOR XML PATH(‘‘)) AS StuList FROM TEST6 A GROUP BY Name ) B
查询结果
参考自:https://www.cnblogs.com/yasuo2/p/6433697.html