温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SQL Server如何使用PIVOT与unPIVOT实现行列转换

发布时间:2022-05-24 17:42:46 来源:亿速云 阅读:330 作者:iii 栏目:开发技术

这篇“SQL Server如何使用PIVOT与unPIVOT实现行列转换”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“SQL Server如何使用PIVOT与unPIVOT实现行列转换”文章吧。

一、sql行转列:PIVOT

1、基本语法:

create table #table1     (    id int ,code varchar(10) , name varchar(20) ); go insert into #table1 ( id,code, name ) values ( 1, 'm1','a' ), ( 2,  'm2',null ), ( 3, 'm3', 'c' ), ( 4,  'm2','d' ), ( 5,  'm1','c' ); go select * from #table1; --方法一(推荐) select PVT.code, PVT.a, PVT.b, PVT.c       from #table1 pivot(count(id) for name in(a, b, c)) as PVT; --方法二 with P as (select * from #table1) select PVT.code, PVT.a, PVT.b, PVT.c       from P        pivot(count(id) for name in(a, b, c)) as PVT; drop table #table1;

结果:

SQL Server如何使用PIVOT与unPIVOT实现行列转换

2、实例:

SQL Server如何使用PIVOT与unPIVOT实现行列转换

3、传统方式:(先汇总拼接出所需列的字符串,再动态执行转列)

先查询出要转为列的行数据,再拼接字符串。

create table #table1     (    id int ,code varchar(10) , name varchar(20) ); go insert into #table1 ( id,code, name ) values ( 1, 'm1','a' ), ( 2,  'm2',null ), ( 3, 'm3', 'c' ), ( 4,  'm2','d' ), ( 5,  'm1','c' ); go select * from #table1; declare @strCN nvarchar(100); select @strCN = isnull(@strCN + ',', '') + quotename(name) from #table1 group by name ; print  @strCN  --‘[a],[c],[d]' declare @SqlStr nvarchar(1000); set @SqlStr = N' select * from #table1 pivot ( count(ID) for name in (' + @strCN + N') ) as PVT'; exec ( @SqlStr ); drop table #table1;

结果:

SQL Server如何使用PIVOT与unPIVOT实现行列转换

二、sql列转行:unPIVOT:

基本语法:

create table #table1 (id int, code varchar(10), name1 varchar(20), name2 varchar(20), name3 varchar(20)); go insert into #table1(id, name1, name2, code, name3) values(1, 'm1', 'a1', 'a2', 'a3'),     (2, 'm2', 'b1', 'b2', 'b3'),     (4, 'm1', 'c1', 'c2', 'c3'); go select * from #table1; --方法一 select PVT.id, PVT.code, PVT.name, PVT.val              from #table1 unpivot(val for name in(name1, name2, name3)) as PVT; --方法二 with P as (select * from #table1) select PVT.id, PVT.code, PVT.name, PVT.val              from P       unpivot(val for name in(name1, name2, name3)) as PVT; drop table #table1;

结果:

SQL Server如何使用PIVOT与unPIVOT实现行列转换

实例:

SQL Server如何使用PIVOT与unPIVOT实现行列转换

以上就是关于“SQL Server如何使用PIVOT与unPIVOT实现行列转换”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI