1.基础表
2.行转列,注意ISNULL函数的使用,在总成绩的统计中,ISNULL(-,0) 有必要使用
3.列转行,对列语文、数学、英语、政治,进行列转行,转为了2列,score scname 这两列,是新列,可以取名为 score11 scname22,随意
4.测试脚本
SELECT * FROM dbo.SC --插入测试数据 INSERT dbo.SC SELECT NEWID(),‘001‘,‘jack1‘,‘数学‘,88 UNION SELECT NEWID(),‘002‘,‘jack2‘,‘语文‘,55 UNION SELECT NEWID(),‘003‘,‘jack3‘,‘英语‘,66 UNION SELECT NEWID(),‘004‘,‘jack4‘,‘政治‘,77 --行转列 SELECT * FROM dbo.SC PIVOT (SUM(Score) FOR SCName IN(语文,数学,英语,政治)) AS p --列转行 SELECT * FROM ( --这里是行转列 SELECT sno,sname,ISNULL(语文,0) AS ‘语文‘,ISNULL(数学,0) AS ‘数学‘,ISNULL(英语,0) AS ‘英语‘,ISNULL(政治,0) AS ‘政治‘ FROM dbo.SC PIVOT (SUM(Score) FOR SCName IN(语文,数学,英语,政治)) AS p ) t UNPIVOT (score FOR SCName IN(语文,数学,英语,政治)) AS up WHERE score !=0 SELECT * FROM ( --这里是行转列 SELECT sno,sname,ISNULL(语文,0) AS ‘语文‘,ISNULL(数学,0) AS ‘数学‘,ISNULL(英语,0) AS ‘英语‘,ISNULL(政治,0) AS ‘政治‘ FROM dbo.SC PIVOT (SUM(Score) FOR SCName IN(语文,数学,英语,政治)) AS p ) t UNPIVOT (Score11 FOR SCName22 IN(语文,数学,英语,政治)) AS up WHERE Score11 !=0
时间: 2024-12-29 01:06:01