意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

SQL Server如何实现行列转换,方法是什么

来源:恒创科技 编辑:恒创科技编辑部
2023-12-19 03:02:59
今天这篇给大家分享的知识是“SQL Server如何实现行列转换,方法是什么”,小编觉得挺不错的,对大家学习或是工作可能会有所帮助,对此分享发大家做个参考,希望这篇“SQL Server如何实现行列转换,方法是什么”文章能帮助大家解决问题。


SQL Server如何实现行列转换,方法是什么

一、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;

结果:

2、实例:

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列转行: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如何实现行列转换,方法是什么”就介绍到这了,如果大家觉得不错可以参考了解看看,如果想要了解更多,欢迎关注恒创科技,小编每天都会为大家更新不同的知识。
上一篇: crossapply与outerapply怎么做连接查询的 下一篇: SQL Server备份与恢复有哪些方式,分别是什么