ALTER PROCEDURE [dbo].[P_Price_avg]
@tblName nvarchar(200),          --要显示的表或多个表的连接 
@topSize int = 7, --这里为天数,取多少天里的数据,默认为7
@strWhere nvarchar(1000) = null --查询条件,不需whereAS
SET NOCOUNT ON --不返回计数Declare @strTmp nvarchar(1000) --存放取得查询结果总数的查询语句if @strWhere is null or @strWhere='' --没有设置显示条件
begin
set @strTmp = 'SELECT co_MPa a,convert(varchar(10),UpdateTime,120) b,avg(co_Price) c FROM '+@tblName
+' WHERE convert(varchar(10),UpDateTime,120) in ' +' (select DISTINCT top '+CAST(@topSize as VARCHAR(10))+' convert(varchar(10),UpDateTime,120)as UpDateTime FROM '+@tblName
+' where 1=1 '
+' order by UpDateTime desc) ' +' GROUP BY co_MPa,convert(varchar(10),UpdateTime,120) '
+' ORDER BY b,a'
end
else
begin
set @strTmp = 'SELECT co_MPa a,convert(varchar(10),UpdateTime,120) b,avg(co_Price) c FROM '+@tblName
+' WHERE convert(varchar(10),UpDateTime,120) in  ' +' (select DISTINCT top '+CAST(@topSize as VARCHAR(10))+' convert(varchar(10),UpDateTime,120)as UpDateTime FROM '+@tblName
+' where 1=1 '+ @strWhere
+' order by UpDateTime desc) '+ @strWhere +' GROUP BY co_MPa,convert(varchar(10),UpdateTime,120) '
+' ORDER BY b,a'
end------返回查询结果-----
exec sp_executesql @strTmp
SET NOCOUNT OFF --返回计数
exec P_Price_avg 'T_Eset_Trade' 下面段的Table须要从过程P_Price_avg得到结果表
set @sql = 'select b '
select @sql = @sql + ' , max(case a when ''' + a + ''' then 分数 else 0 end) [' + a + ']'
from (select distinct a from Tabel) as aa
set @sql = @sql + ' from tb group by b'
exec(@sql) 
如何做,谢谢,最好不要存临时表的办法。