日期:2014-05-17 浏览次数:20648 次
create table t1
(
code varchar(10),
indexcode varchar(10)
)
insert into t1
select '200901', 'F23' union all
select '200901', 'F34' union all
select '200901', 'F56' union all
select '200901', 'T67' union all
select '200902', 'F23' union all
select '200902', 'F34' union all
select '200902', 'T67' union all
select '200902', 'T89' union all
select '200903', 'F56' union all
select '200903', 'F45' union all
select '200903', 'TP25' union all
select '200903', 'TP45'
go
select distinct indexcode,rid=identity(int,1,1)
into #tb
from t1
declare @sql varchar(8000) --第一个拼接字符串
declare @str varchar(8000) --第二个拼接字符串
set @sql=' select code '
select @sql=@sql+' ,max(case when indexcode='''+indexcode+''' then 1 else 0 end) as ['+indexcode+']'
from #tb
where rid between 1 and 4
select @str = isnull(@str,'')+' ,max(case when indexcode='''+indexcode+''' then 1 else 0 end) as ['+indexcode+']'
from #tb
where rid between 5 and 8
exec (@sql+@str+' from t1 group by code')
drop table t1,#tb
/***************
code &n