1.基础表
2.行转列,注意ISNULL函数的使用,在总成绩的统计中,ISNULL(-,0) 有必要使用
3.列转行,对列语文、数学、英语、政治,进行列转行,转为了2列,score scname 这两列,是新列,可以取名为 score11 scname22,随意
4.测试脚本
SELECT * FROM dbo.SC--插入测试数据INSERT dbo.SC SELECT NEWID(),'001','jack1','数学',88UNIONSELECT NEWID(),'002','jack2','语文',55UNIONSELECT NEWID(),'003','jack3','英语',66UNIONSELECT NEWID(),'004','jack4','政治',77--行转列SELECT * FROM dbo.SCPIVOT (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) tUNPIVOT (score FOR SCName IN(语文,数学,英语,政治)) AS upWHERE score !=0SELECT * 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) tUNPIVOT (Score11 FOR SCName22 IN(语文,数学,英语,政治)) AS upWHERE Score11 !=0