SQLServer行列互转实现思路(聚合函数)
有时候会碰到行转列的需求(也就是将列的值作为列名称),通常我都是用CASEEND+聚合函数来实现的。
如下:
declare@ttable (StudentNamenvarchar(20), Subjectnvarchar(20), Scoreint) Insertinto@t(StudentName,Subject,Score)values('学生A','中文',80); Insertinto@t(StudentName,Subject,Score)values('学生A','数学',78); Insertinto@t(StudentName,Subject,Score)values('学生A','英语',92); Insertinto@t(StudentName,Subject,Score)values('学生B','中文',89); Insertinto@t(StudentName,Subject,Score)values('学生B','数学',87); Insertinto@t(StudentName,Subject,Score)values('学生B','英语',75); Insertinto@t(StudentName,Subject,Score)values('学生C','中文',92); Insertinto@t(StudentName,Subject,Score)values('学生C','数学',74); Insertinto@t(StudentName,Subject,Score)values('学生C','英语',65); Insertinto@t(StudentName,Subject,Score)values('学生D','中文',79); Insertinto@t(StudentName,Subject,Score)values('学生D','数学',83); Insertinto@t(StudentName,Subject,Score)values('学生D','英语',81); Insertinto@t(StudentName,Subject,Score)values('学生E','中文',73); Insertinto@t(StudentName,Subject,Score)values('学生E','数学',84); Insertinto@t(StudentName,Subject,Score)values('学生E','英语',93); Insertinto@t(StudentName,Subject,Score)values('学生F','中文',79); Insertinto@t(StudentName,Subject,Score)values('学生F','数学',86); Insertinto@t(StudentName,Subject,Score)values('学生F','英语',84); selectStudentName, sum(casewhenSubject=N'中文'thenScoreelse0end)Chinese, sum(casewhenSubject=N'数学'thenScoreelse0end)Math, sum(casewhenSubject=N'英语'thenScoreelse0end)Engilsh from@t groupbyStudentName
今天看到一个新的写法,pivot可以实现相同的功能(2005才开始支持)。
pivot的语法为:
table_source
pivot(聚合函数(value_column)pivot_columnfor(columnlist))
稍微解释一下:
table_source:是我们要进行转换的表。pivot_column:就是要进行行转列的列名。value_column:是转换后列的值。columnlist是要生成的列。
同样是上面的例子,使用pivot可以这样写得到同样的结果:
selectStudentName, [中文]Chinese, [数学]Math, [英语]English from (select*from@t)t1 pivot(sum(Score)forSubjectin([中文],[英语],[数学]))t2
与之对应的unpivot就是列转行了(列名作为值),
unpivot的语法为:
table_source
unpivot(value_columnubpivot_columnfor(columnlist))
参数的意义与pivot是一样的。这里我们可以简单的把刚刚转后的再转回去,这样就得到原来的表了:
selectStudentName, Subject, Score from (select*from@t)t1 pivot(sum(Score)forSubjectin([中文],[英语],[数学]))t2 unpivot(ScoreforSubjectin([中文],[英语],[数学]))t3
以上就是本文的全部内容,希望对大家学习实现SQLServer行列互转有所帮助。