加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQLServer行列互转实现思路(聚合函数)

发布时间:2020-12-12 09:16:35 所属栏目:MsSql教程 来源:网络整理
导读:有时候会碰到行转列的需求(也就是将列的值作为列名称),通常我都是用 CASE END + 聚合函数来实现的。 如下: Insert into @t (StudentName,Subject,Score) values ( '学生A','中文',80 ); Insert into @t (StudentName,'数学',78 ); Insert into @t (Stude

有时候会碰到行转列的需求(也就是将列的值作为列名称),通常我都是用 CASE END + 聚合函数来实现的。

如下:

Insert into @t (StudentName,Subject,Score) values ( '学生A','中文',80 );
Insert into @t (StudentName,'数学',78 );
Insert into @t (StudentName,'英语',92 );
Insert into @t (StudentName,Score) values ( '学生B',89 );
Insert into @t (StudentName,87 );
Insert into @t (StudentName,75 );
Insert into @t (StudentName,Score) values ( '学生C',74 );
Insert into @t (StudentName,65 );
Insert into @t (StudentName,Score) values ( '学生D',79 );
Insert into @t (StudentName,83 );
Insert into @t (StudentName,81 );
Insert into @t (StudentName,Score) values ( '学生E',73 );
Insert into @t (StudentName,84 );
Insert into @t (StudentName,93 );
Insert into @t (StudentName,Score) values ( '学生F',86 );
Insert into @t (StudentName,84 );

select StudentName,sum(case when Subject = N'中文' then Score else 0 end) Chinese,sum(case when Subject = N'数学' then Score else 0 end) Math,sum(case when Subject = N'英语' then Score else 0 end) Engilsh
from @t
group by StudentName

今天看到一个新的写法,pivot 可以实现相同的功能(2005才开始支持)。

pivot 的语法为:

稍微解释一下:

table_source:是我们要进行转换的表。pivot_column: 就是要进行行转列的列名。

是转换后列的值。columnlist 是要生成的列。

同样是上面的例子,使用pivot 可以这样写得到同样的结果:

与之对应的 unpivot 就是列转行了(列名作为值),

unpivot 的语法为:

table_source

unpivot(value_column ubpivot_column for(columnlist))

参数的意义与pivot 是一样的。这里我们可以简单的把刚刚转后的再转回去,这样就得到原来的表了:

以上就是本文的全部内容,希望对大家学习实现SQLServer行列互转有所帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读