日期:2014-05-17 浏览次数:20639 次
--给你提供一种方法,适合不固定列的行列转换
create table t(年份 varchar(20), 月份 varchar(20), 收入 float)
insert into t
select '2011','1月',200 union all
select '2011','2月',300 union all
select '2011','3月',500 union all
select '2012','1月',600 union all
select '2012','2月',700
--select * From @t
declare @sql varchar(8000)
set @sql='select 年份'
select @sql=@sql+ ',max(case 月份 when '''+月份+''' then 收入 end) as ['+月份+']' from (select distinct 月份 from t) as A
set @sql=@sql+' from t group by 年份 order by 年份'
exec (@sql)
drop table t
/*
年份 1月 2月 3月
------ ------ ------ ------
2011 200 300 500
2012 600 700 null
(2 个数据列受到影响)
*/