我有两个名为Emp
和TrainingTable
Emp
列(EmpId(PK, int, not null), EmpName(nchar(10), null)
)TrainingTable
列(EmpId(FK, int, null), TainingId(int, null), TainingName(nvarchar(50), not null)
)代码:
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)
现在我要做的是使用Training1,Traning2,..等重命名列1,2,3 .. 结果表可能会根据数据而改变。列可能会增加..
我几乎尝试了所有事情......但没有找到正确的方法来实现它。
答案 0 :(得分:0)
试试这个
您需要使用CAST()
来转换列 DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME('Training' + CAST(TainingId AS Varchar(50)))
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,
col = ''Training'' + cast(TainingId as varchar(10))
from TrainingTable
INNER JOIN Emp ON TrainingTable.EmpId = Emp.EmpId
) x
pivot
(
max(TainingName)
for col in (' + @cols + ')
) p '
execute(@query)