SQL Server如何实现行列转换,方法是什么
Admin 2022-08-03 群英技术资讯 1407 次浏览
今天这篇给大家分享的知识是“SQL Server如何实现行列转换,方法是什么”,小编觉得挺不错的,对大家学习或是工作可能会有所帮助,对此分享发大家做个参考,希望这篇“SQL Server如何实现行列转换,方法是什么”文章能帮助大家解决问题。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;
结果:


先查询出要转为列的行数据,再拼接字符串。
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;
结果:

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;
结果:


免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
在数据查询中,从2008开始SQLServer提供了一个新的数据类型hierarchyid,专门用来操作层次型数据结构。hierarchyid 类型对层次结构树中有关单个节点的信息进行逻...
由于项目起初用的是sqlserver数据库,后来改用了mysql数据库,那么如何把sqlserver迁移mysql呢?对sqlserver数据库迁移感兴趣的朋友可以参考下本篇文章
这篇文章主要介绍了SqlServer数据库远程连接案例教程,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
sql连接服务器失败是因为数据库引擎没有启动,其解决办法:首先依次点击“开始->程序->Microsoft SQL Server 2008->SQL Server 2008外围应用配置器”;然后单击“服务”并选择启动即可。
SQL Server 对于数据平台的开发者来说越来越友好,下面这篇文章主要给大家介绍了关于SQLServer中JSON文档型数据的查询问题的解决方法,需要的朋友可以参考下
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008