我有一张桌子:
EntityID AttributeID OptionText 5016 20 Paintings 5044 18 Female 5060 48 M 5060 48 F 5060 49 Apple 5060 49 Banana 5060 49 Cat
我想创建一个将显示的视图:
5016 20 Paintings 5044 18 Female 5060 48 M,F 5060 49 Apple,Banana,Cat
均值每个实体上的属性值应以逗号分隔.
选项的数量可以变化.
任何帮助是赞赏!
解决方法
对于EntityID的每一对,AttributeID使用XML路径技巧生成CSV
SELECT M.EntityID,M.AttributeID,SUBSTRING(CAST(foo.bar AS varchar(8000)),2,7999) AS Options FROM ( SELECT DISTINCT EntityID,AttributeID FROM MyTable ) M CROSS APPLY ( SELECT ',' + OptionText FROM MyTable M2 WHERE M.EntityID = M2.EntityID AND M.AttributeID= M2.AttributeID FOR XML PATH ('') ) foo(bar)