一维转二维 Create Table #JJ
(
OrderNo Varchar(12),
ColorDesc Varchar(50),
Sizx Varchar(8),
Qty Int
)
Insert into #jj (OrderNo,ColorDesc,Sizx,Qty)
Select
POPackingDetail.OrderNo,
POColor.ColorDesc,
POPackingDetail.Sizx,POPackingDetail.Qty
from
POPackingDetail inner join POColor on POColor.ColorID=POPackingDetail.ColorID and POColor.OrderNo=POPackingDetail.OrderNo
where
POPackingDetail.OrderNo='105800A'
Select * from #jj
Declare @sql Varchar(8000)
Set @sql='Select OrderNo,ColorDesc'
Select @sql=@sql+',['+dd+']=sum (case Sizx when ''+dd+'' then Qty else 0 end)'
from (Select distinct dd=Sizx from #jj) ss
Set @sql=@sql+'from #jj Group by OrderNo,ColorDesc'
Exec(@sql)
set @str='select * from #jj pivot(max(qty) for sizx in ('+@sizx+') as b'
exec(@str) ------解决方案-------------------- set @str='select * from #jj pivot(max(qty) for sizx in ('+@sizx+')) as b'
补了个括号。 ------解决方案-------------------- 这个是完整的:
declare @sizx varchar(2000)='',@str varchar(max)=''
select @sizx=@sizx+','+quotename(sizx) from #A group by sizx
select @sizx=STUFF(@sizx,1,1,'')
set @str='select * from #jj pivot(max(qty) for sizx in ('+@sizx+')) as b'