基本语法
select * from Mould pivot ( count(ID)for ProductTypeCode in ( [FC], [RCU], [RCD] )) as PVT; with P
as ( select * from Mould )
select * from P pivot ( count(ID)for ProductTypeCode in ( [FC], [RCU], [RCD] )) as PVT;
一、sql行转列PIVOT:
二、sql列转行unPIVOT:
三、动态执行
先查询出要转为列的行数据,然后设置格式,再拼接字符串。
declare @strCN nvarchar(100);
select @strCN = isnull(@strCN + ',', '') + quotename(ProductTypeCode) from Mould group by ProductTypeCode;
declare @SqlStr nvarchar(1000); set @SqlStr = N'
select * from Mould pivot ( count(ID)for ProductTypeCode in (' + @strCN + N') ) as PVT';
exec ( @SqlStr );
go