Thursday, 20 December 2012

Convert Row to column using sqlserver


declare @col as nvarchar(max),
@query as nvarchar(max);

set @col=Stuff((select distinct ','+ wl.WI_Projname from WorklogTable as wl for xml path(''),type).value('.','nvarchar(max)'),1,1,'')
set @query ='select WL_Staffcode,name,' + @col + ' from(
select WL_Staffcode,
staff.Staff_Name as name,
Wl_Hours ,WI_Projname from WorklogTable as wl inner join
StaffMaster as staff on staff.Staff_Code=wl.WL_Staffcode
) x
pivot(sum(Wl_Hours)for WI_Projname in ('+@col+'))p'

print @query

No comments:

Post a Comment