本文整理自网络,侵删。
一、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;
结果:
相关阅读 >>
navicat连接sql server报错08001如何解决
更多相关阅读请进入《sql》频道 >>

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