日期:2014-05-18  浏览次数:20464 次

行列转置加平均值
请大家给我看下以下语句为何报错,谢谢大家了!
消息 102,级别 15,状态 1,第 2 行
'/' 附近有语法错误。
消息 102,级别 15,状态 1,第 3 行
'n' 附近有语法错误。


declare @sql varchar(8000)
select @sql = isnull(@sql + ',' , '') + Class from Elearning_AnswerSheet group by Class
exec ('select m.* , n.平均分 from
(select * from (select Store,Name,Code,Mark from Elearning_AnswerSheet) a pivot (AVG(Mark) for Class in (' + @sql + ')) b) m , 
(select Store,Name,Code,avg(Mark) as 平均分 from Elearning_AnswerSheet group by Store,Name,Code) n
where m.Store = n.Store and m.Name=n.Name and m.Code=n.Code')

------解决方案--------------------
SQL code

declare @sql varchar(8000)
select @sql = isnull(@sql + ',' , '') + Class from Elearning_AnswerSheet group by Class
exec ('select m.* , n.平均分 from
(select * from (select Store,Name,Code,Mark from Elearning_AnswerSheet) a pivot (AVG(Mark) for Class in (' + @sql + ')) b) m ,  
(select Store,Name,Code,avg(Mark) as 平均分 from Elearning_AnswerSheet group by Store,Name,Code) n 
   where m.Store = n.Store and m.Name=n.Name and m.Code=n.Code) tb ')


--try

------解决方案--------------------
SQL code
declare @sql varchar(8000)
select @sql = isnull(@sql + '],[' , '') +  Class from Elearning_AnswerSheet group by Class 
set @sql =  '[' + @sql + ']'
exec ('select m.* , n.平均分 from
(select * from (select Store,Name,Code,Mark from Elearning_AnswerSheet) a pivot (AVG(Mark) for Class in (' + @sql + ')) b) m ,  
(select Store,Name,Code,avg(Mark) as 平均分 from Elearning_AnswerSheet group by Store,Name,Code) n
where m.Store = n.Store and m.Name=n.Name and m.Code=n.Code')