关于for xml path('')

今天在项目中遇到一个问题,在综合查询的时候,需要把同一个表中,同一个人的某个属性加起来放在一个字段中,这时候需要for xml path('')

select * from t_Baseinfo bi 
left join 
(     
  select DISTINCT b.PersonID,
     STUFF(
	(
	     select ','+ a.Features  from t_Special a where a.PersonID=b.PersonID and flag=1 for xml path('')
       ),1,1,'') as features  
     from t_Special b
)tfeatures on bi.ID=tfeatures.PersonID 
  where Flag=1 and tfeatures.Features like '%眼%'

 其中,先使用  select ','+ a.Features from t_Special a for xml path(''),把需要放在一个字段中的属性用‘,’拼接放在xml中,

人后用stuff截掉第一个‘,’,起别名 features,由于需要把表中同一personid显得字段防盗一个里  所以需要加上 where a.PersonID=b.PersonID  条件。这样他会根据b表中personid来取值。

 

参考资料:http://www.cnblogs.com/doubleliang/archive/2011/07/06/2098775.html

posted @ 2016-06-29 18:40  木丶子  阅读(1466)  评论(0)    收藏  举报