I have two tables named Emp
and TrainingTable
Emp
columns (EmpId(PK, int, not null), EmpName(nchar(10), null)
)TrainingTable
columns (EmpId(FK, int, null), TainingId(int, null), TainingName(nvarchar(50), not null)
)
Code:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(TainingId)
from TrainingTable
group by TainingId
order by TainingId
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT EmpName,' + @cols + ' from
(
select Emp.EmpName, TainingName, TainingId
from TrainingTable INNER JOIN Emp ON TrainingTable.EmpId = Emp.EmpId
) x
pivot
(
max(TainingName)
for TainingId in (' + @cols + ')
) p '
execute(@query)
Now what I want to do is to rename the columns 1,2,3.. with Training1,Traning2,.. and so on.. the result table may change depending on data. columns may increase..
I tried almost every thing .. but not getting the correct way to achieve it.