SQL Server如何实现行列转换,方法是什么
Admin 2022-08-03 群英技术资讯 938 次浏览
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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
MySQL安装完成后,需要启动服务进程,否则客户端无法连接数据库。在前面的配置过程中,已经将MySQL安装为Windows服务,当Windows启动时MySQL服务也会随着启动,然而有时需要手动控制MySQL服务的启动与停止,此时可以通过两种方式来实现。
这篇文章主要介绍SQL Server中怎么样实现数字辅助表的内容,一些朋友可能不是很了解数字辅助表,其实数字辅助表有很大的用处,接下来我们一起来了解看看SQL Server 实现数字辅助表的方法。
文章目录遇到的问题使用SQLServerProfiler监控数据库SQL1:查找最新的30条告警事件SQL2:获取当前的总报警记录数...
参考php手册,对php连接sql server系列做出个小结。主要有五种方式:
文本给大家分享的是关于sqlserver日志传送的内容,主要介绍sqlserver日志传送的概念、优点、方法等等,具有一定的参考价值,感兴趣的朋友就跟随小编一起看看吧。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008