加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

For XML Path

发布时间:2020-12-16 09:06:24 所属栏目:百科 来源:网络整理
导读:关于For XML Path的用法 创建的表数据如图: 先看下for xml path的初始用法:select ClassID,Sex,Age,Name from #PersonInfo for xml path('PersonInfo') 从名字就看可以看出用法,for xml !!! 在使用过程中感觉通常是恶group by 一起用的。举例如下: --统
关于For XML Path的用法
创建的表数据如图:

先看下for xml path的初始用法:select ClassID,Sex,Age,Name from #PersonInfo for xml path('PersonInfo')
从名字就看可以看出用法,for xml !!!

在使用过程中感觉通常是恶group by 一起用的。举例如下:
--统计每个班中超过22岁的男同学信息
select ClassID,COUNT(1) as '超过22岁个数',(select Name+',' from #PersonInfo where ClassID=p.ClassID for xml path ('')) as '姓名集合'
from #PersonInfo p where Sex='男' and Age>22 group by ClassID order by ClassID
select ClassID,(select Name+',' from #PersonInfo where ClassID=p.ClassID and Age=p.Age for xml path ('')) as '姓名集合'
from #PersonInfo p where Sex='男' and Age>22 group by ClassID,Age order by ClassID
select ClassID,(select Name+',' from #PersonInfo where ClassID=p.ClassID and Age=p.Age for xml path ('')) as '姓名集合'
from #PersonInfo p where Sex='男' group by ClassID,Age having Age>22 order by ClassID

结果如下:

感觉having的用处没有想象中那么大。只有在group by后使用,并且是聚合函数是用处才大,不然直接写在where后面即可。
补充一下:姓名集合最后面的逗号可以通过stuff函数去除掉。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读