日期:2014-05-18 浏览次数:20460 次
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 F23 F34 F45 F56 T67 T89 TP25 TP45 ---------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- 200901 1 1 0 1 1 0 0 0 200902 1 1 0 0 1 1 0 0 200903 0 0 1 1 0 0 1 1 (3 行受影响)