我想避免在SQL Server中使用动态数据透视

时间:2015-05-28 11:28:05

标签: sql-server-2008 sql-server-2008-r2 dynamic-pivot

我正在使用像这样的动态支点

declare @pivot varchar(max)
declare @column varchar(max)

SELECT @column= ISNULL(@column + ',','') +
       QUOTENAME(METRIC_CD)
       FROM (select Distinct METRIC_CD from  EFRDS.FCT_STAFF_METRIC f join EFRDS.DIM_SCORE_METRIC  m on f.METRIC_KEY=m.METRIC_KEY) AS Courses

declare  @column1 varchar(max)

select @column1= ISNULL(@column1 ,'') + 'Max('+QUOTENAME(METRIC_CD)+ ') as '+QUOTENAME(METRIC_CD)+','
       FROM (select Distinct METRIC_CD from  EFRDS.FCT_STAFF_METRIC f join EFRDS.DIM_SCORE_METRIC  m on f.METRIC_KEY=m.METRIC_KEY) AS Courses
       set @column1= STUFF(@column1,len(@column1),1,'')

set @pivot='select school_year ,YEAR_KEY,DISTRICT_KEY,SCHOOL_KEY,TEAM_KEY,STAFF_KEY,min_score,max_Score,'+@column1+' 
from
(
select f.*,METRIC_CD,m.SCHOOL_YEAR
from EFRDS.FCT_STAFF_METRIC f
join EFRDS.DIM_SCORE_METRIC  m on f.METRIC_KEY=m.METRIC_KEY
)p
pivot(sum(value) for METRIC_CD in('+@column+')) as pvt 
group by school_year ,YEAR_KEY,DISTRICT_KEY,SCHOOL_KEY,TEAM_KEY,STAFF_KEY,min_score,max_Score' 
exec (@pivot)

而不是使用

pivot(sum(value) for METRIC_CD in('+@column+')) as pvt 

我想用

pivot(sum(value) for METRIC_CD in (  select ISNULL(@column + ',','') +
               QUOTENAME(METRIC_CD)
               FROM (select Distinct METRIC_CD from  EFRDS.FCT_EVALUATE_METRICS f join EFRDS.DIM_SCORE_METRIC ) m on f.METRIC_KEY=m.METRIC_KEY) as g

但我正面临这个问题

  

错误的语法在'选择' .expecting'。',ID或Quoted_id。

0 个答案:

没有答案