日期:2014-05-18 浏览次数:20538 次
drop table t1 create table t1(id varchar(10),cusno varchar(10),price numeric(10,2)) insert t1 select 'S012','A',35.02 union all select 'S012','C',38.60 union all select 'S013','A',52.00 Declare @S Varchar(8000) Select @S='Select ID,' Select @S=@S + 'SUM(Case Cusno When '''+ Cusno+ ''' Then Price Else 0.00 End) As Price' + Cusno From t1 Group By Cusno Select @S = @S + ' From t1 Group By ID ' EXEC(@S) GO
drop table t1 create table t1(id varchar(10),cusno varchar(10),price numeric(10,2)) insert t1 select 'S012','A',35.02 union all select 'S012','C',38.60 union all select 'S013','A',52.00 Declare @S Varchar(8000) Select @S='Select ID' Select @S=@S + ',SUM(Case Cusno When '''+ Cusno+ ''' Then Price Else 0.00 End) As Price' + Cusno From t1 Group By Cusno Select @S = @S + ' From t1 Group By ID ' exec(@S) GO /* ID PriceA PriceC ---------- ---------------------------------------- ---------------------------------------- S012 35.02 38.60 S013 52.00 .00 */
------解决方案--------------------
declare @s varchar(8000)
set @s='select id'
select @s=@s +',sum(case cusno when '''+cusno+''' then price else 0.00 end) as price'+cusno
from t1 group by cusno
select @s=@s+' from t1 group by id'
exec (@s)