Wednesday, July 2, 2014

Pivot trouble

Incase if the period varies


try dynamic pivot



select * into #temp11 from
(select '200101' period ,'30' id ,'1568' qt union all
select '200102','30','2330' union all
select '200103','30','1550' union all
select '200102','28','650' )a

declare @columns varchar(200) = '',@sql varchar(200) =''
select @columns += ','+ quotename(period) from (select distinct period from #temp11) a


select @sql ='select * from #temp11
pivot (max(qt) for period in('+stuff(@columns,1,1,'')+')) a'
exec(@sql)


No comments:

Post a Comment