Wednesday, March 19, 2014

Pivot Table in Sql server

declare @date datetime,@ss varchar(500)='',@ss1 varchar(500)
 declare curs_c cursor for select   Distinct workdate from tblprojecttime
 open curs_c
FETCH NEXT FROM curs_c INTO @date
 while @@FETCH_STATUS=0
 begin
 if(@ss='')
 set @ss='['+cast(@date as varchar(12))+']'
 else
  set @ss=@ss+','+'['+cast(@date as varchar(12))+']'
FETCH NEXT FROM curs_c INTO @date
 end
 close curs_c
 deallocate  curs_c
 print @ss

  set @ss1=N'select * from (select  projectid,taskid,workdate,workhours from tblprojecttime)
 as ss pivot(  Sum(workhours) for workdate in('+@ss +') )as PivotTable'
 
  execute (@ss1)



No comments:

Post a Comment