发布时间:2018-10-24编辑:admin阅读(1842)
CREATE TABLE StudentScores ( UserName VARCHAR(20), --学生姓名 Subject VARCHAR(30), --科目 Score INT --成绩 ) INSERT INTO StudentScores SELECT '张三', '语文', 80 INSERT INTO StudentScores SELECT '张三', '数学', 90 INSERT INTO StudentScores SELECT '张三', '英语', 70 INSERT INTO StudentScores SELECT '张三', '生物', 85 INSERT INTO StudentScores SELECT '李四', '语文', 80 INSERT INTO StudentScores SELECT '李四', '数学', 92 INSERT INTO StudentScores SELECT '李四', '英语', 76 INSERT INTO StudentScores SELECT '李四', '生物', 88 INSERT INTO StudentScores SELECT '王五', '语文', 60 INSERT INTO StudentScores SELECT '王五', '数学', 82 INSERT INTO StudentScores SELECT '王五', '英语', 96 INSERT INTO StudentScores SELECT '王五', '生物', 78 SELECT * FROM dbo.StudentScores
SELECT UserName, value=(STUFF((SELECT ','+Subject FROM StudentScores WHERE UserName=Test.UserName FOR XML PATH('')), 1, 1, '')) FROM StudentScores AS Test GROUP BY UserName;
PS:STUFF语句就是为了去掉第一个【逗号】
附STUFF用法:(从原字符的第二个开始共三个字符替换为后面的字符)
SELECT STUFF('abcdefg', 2, 3, '12345');
查询结果:a12345efg
静态SQL:
SELECT * FROM StudentScores PIVOT(SUM(Score) FOR Subject IN(生物, 数学, 英语, 语文))T;
动态SQL:
DECLARE @sql VARCHAR(8000); SELECT @sql=ISNULL(@sql+',', '')+Subject FROM StudentScores GROUP BY Subject; SET @sql='SELECT * FROM StudentScores PIVOT(SUM(Score) FOR Subject IN('+@sql+'))T;'; EXEC(@sql);
测试数据从行转列结果来。
静态SQL:
SELECT P.UserName, P.Subject, P.Score FROM(SELECT * FROM StudentScores PIVOT(SUM(Score) FOR Subject IN(生物, 数学, 英语, 语文))T)X UNPIVOT(Score FOR Subject IN(生物, 数学, 英语, 语文))P;
动态SQL:
DECLARE @sql VARCHAR(8000); SELECT @sql=ISNULL(@sql+',', '')+Subject FROM StudentScores GROUP BY Subject; SET @sql='SELECT P.UserName, P.Subject, P.Score FROM(SELECT * FROM StudentScores PIVOT(SUM(Score) FOR Subject IN('+@sql+'))T)X UNPIVOT(Score FOR Subject IN('+@sql+'))P;'; EXEC(@sql);
下一篇:YEPO笔记本重装系统
0人
0人
0人
0人