ForXMLPath
關於For XML Path的用法
創建的表數據如圖:
先看下fZ喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vciB4bWwgcGF0aLXEs/XKvNPDt6ijunNlbGVjdCBDbGFzc0lELFNleCxBZ2UsTmFtZSBmcm9tICNQZXJzb25JbmZvIGZvciB4bWwgcGF0aCg="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,Age,COUNT(1) as '超過22歲個數',
(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,Age,COUNT(1) as '超過22歲個數',
(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函數去除掉。