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;

结果:

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;

结果:

阅读剩余部分

相关阅读 >>

asp.net2.0数据库入门之sqldatasource

sql增加字段的语句是什么

pymssql数据库操作mssql2005实例分析

如何使用sql同时更新多个字段?

mysql窗口函数的具体使用

详解sql中group by的用法

sql语句添加删除修改字段、一些表与字段的基本操作、数据库备份等

sql注入之必备的基础知识

通过批处理调用sql的方法(osql)

如何进行sql注入

更多相关阅读请进入《sql》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

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

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

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

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

评论

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