日期:2014-05-17 浏览次数:20500 次
DECLARE @tb TABLE(NAME VARCHAR(20),Course VARCHAR(20),Score INT)
INSERT INTO @tb
select '张三','物理', 70 union all
select '张三','化学' ,80 union all
select '李四', '地理', 78 union all
select '李四', '物理' ,88 union all
select '王五', '物理', 67 union all
select '王五', '化学', 89
DECLARE @str NVARCHAR(4000)=''
SELECT name+xmlStr+e FROM (
SELECT name='<row NAME='''+NAME+'''><Name>',xmlStr=(SELECT Course,Score FROM @tb WHERE t1.NAME=NAME FOR XML PATH('')),
e='</Name></row>'
FROM @tb t1
GROUP BY t1.NAME
) t
/*
------------------------------------------------
<row NAME='李四'><Name><Course>地理</Course><Score>78</Score><Course>物理</Course><Score>88</Score></Name></row>
<row NAME='王五'><Name><Course>物理</Course><Score>67</Score><Course>化学</Course><Score>89</Score></Name></row>
<row NAME='张三'><Name><Course>物理</Course><Score>70</Score><Course>化学</Course><Score>80</Score></Name></row>
(3 行受影响)
*/