For XML Path,forxmlpath
關於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 ClassIDselect 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 ClassIDselect 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函數去除掉。