一个动态SQL实现纵向列变横向的例子create table t(id varchar(10),years int,quantity int)
insert into t(id,years,quantity)
select '100002', 2001, 100 union all
select '100002', 2002, 200 union all
select '100002', 2003, 300 union all
select '100003', 2001, 400 union all
select '100003', 2002, 500 union all
select '100003', 2003, 600 union all
select '100004', 2001, 700 union all
select '100004', 2002, 800
go
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',sum(case years when '+cast(years as varchar)+' then quantity else 0 end) ['+cast(years as varchar)+']'
from t group by years
exec('select id'+@sql+' from t group by id order by id')
drop table t稍微改一下就可以了