我创建了这个sql动态字符串但是在运行时此错误显示"关键字附近的语法错误' FOR'。"
declare @cols as nvarchar(max)
,@query as nvarchar(max);
set @cols = stuff(
(select distinct ','+quotename(MatName) from viewProjVsMat
FOR xml path(''),type).value('.','nvarchar(max)')
,1,1,'');
set @query = 'select ProjName
,'+@cols+'
from viewProjVsMat
pivot (Monut for MatName in ('+@cols+')
) p';
execute(@query)
答案 0 :(得分:1)
问题在于
行pivot (Monut for MatName in ('+@cols+')
此处,Monut
需要包含在聚合函数中,例如sum,max,avg等。
例如:
pivot (SUM(Monut) for MatName in ('+@cols+')
有关PIVOT的更多信息,请参阅here。
答案 1 :(得分:0)
使用聚合函数取决于您的要求,如AVG,Min,Max
pivot (
AVG(Monut) for MatName in ('+@cols+')
) p';
您修改后的代码
declare @cols as nvarchar(max)
,@query as nvarchar(max);
set @cols =
stuff(
(select distinct ','+quotename(MatName) from viewProjVsMat
FOR xml path(''),type).value('.','nvarchar(max)')
,1,1,'');
set @query = 'select ProjName
,'+@cols+'
from viewProjVsMat
pivot (
AVG(Monut) for MatName in ('+@cols+')
) p';
execute(@query)
Print @query