sql行列转换PIVOT与unPIVOT

时间:2022-12-28 16:43:43

基本语法

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行列转换PIVOT与unPIVOT

二、sql列转行unPIVOT:

sql行列转换PIVOT与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