我的T_Award数据表的内容是这个样子
我使用了这样的SQL函数使数据这样分组的显示出来了
1 select typename, awardname = stuff((select ',' + awardname from T_Award t where typename = T_Award.typename for xml path('')) , 1 , 1 , '') 2 from T_Award 3 group by typename
结果是这个样子
然后我在使用一个多表查询的时候使用的SQL语句是这个样子
1 select a.personName,d.awardName ,c.activityName,d.typeName 2 from T_Person a 3 join T_PersonAwardR b 4 on a.id=b.personId 5 join T_Activity c 6 on b.activityId=c.id 7 join T_Award d 8 on d.id=b.awardId 9 where c.activityName='万人长跑大赛' and d.typeName='优秀主持人奖';
这样我的查询结果是这个样子
然后我想仿照着第一个例子的语句使我的数据这样显示
仿照一下午了,就是写不对,请大家帮帮忙吧!谢谢!!!!!
with awardT as( select a.personName,d.awardName ,c.activityName,d.typeName from T_Person a join T_PersonAwardR b on a.id=b.personId join T_Activity c on b.activityId=c.id join T_Award d on d.id=b.awardId where c.activityName='万人长跑大赛' and d.typeName='优秀主持人奖' ) select B.awardName,LEFT(awards,LEN(awards)-1) as awards FROM ( SELECT awardName, (SELECT personName+',' FROM awardT WHERE awardName=A.awardName for xml path('')) as awards from awardT A group by awardName ) B
谢谢啦!
SELECT a.awardnaame , STUFF(( SELECT ',' + table1.personname FROM table1 WHERE table1.awardnaame = a.awardnaame FOR XML PATH('') ), 1, 1, '') AS personname FROM ( SELECT awardnaame FROM table1 GROUP BY awardnaame ) a
SELECT a.awardnaame ,
STUFF(( SELECT ',' + table1.personname
FROM table1
WHERE table1.awardnaame = a.awardnaame
FOR
XML PATH('')
), 1, 1, '') AS personname
FROM ( SELECT awardnaame
FROM table1
GROUP BY awardnaame
) a