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


当前第2页 返回上一页

二、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内容来自木庄网络博客


打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...