日期:2014-05-18 浏览次数:20933 次
create table [3DSource] (Team int not null, Chid int not null, Dvlue float null ) insert into [3DSource] select 1,1,23.5 union all select 2,2,21.2 union all select 2,3,26.8 union all declare @s varchar(8000) set @s = ' ' select @s = @s+ ',['+convert(varchar(8),Chid)+']=Sum(case when Chid= '+convert(varchar(8),Chid)+' then Dvlue end) ' from (select Cast(Chid As VarChar) As Chid from [3DSource] group by [3DSource].Chid) a print 'select Team '+@s+ ' from [3DSource] group by Team' set @s='select Team '+@s+ ' from [3DSource] group by Team' print @s exec(@s) Team 1 2 3 ----------- ---------------------- ---------------------- ---------------------- 1 23.5 NULL NULL 2 NULL 21.2 26.8 警告: 聚合或其他 SET 操作消除了空值。 (2 行受影响)
------解决方案--------------------
declare @s varchar(8000) set @s = ' ' select @s = isnull(@s+ ',','')+' Sum(case when Chid= '''+ltrim(Chid)+''' then (Dvalue) else 0 end) as ['+ltrim(Chid)+']' from (select Cast(Chid As VarChar(10)) As Chid from [3DSource] group by [3DSource].Chid) a --print @s set @s='select Team '+@s+ ' from [3DSource] group by Team' print @s exec(@s)