日期:2014-05-18 浏览次数:20486 次
create table tb(AA int,BB varchar(1),CC varchar(1)) insert into tb select 1,'a','A' union all select 1,'a','B' union all select 1,'b','A' union all select 1,'b','C' union all select 2,'a','C' union all select 2,'a','B' declare @sql varchar(8000) set @sql='select AA, ' select @sql= @sql+'max(case when CC='''+ltrim(CC) +''' then BB else ''-'' end) as '+ltrim(CC)+',' from (select distinct CC from tb) a set @sql=left(@sql,len(@sql)-1)+' from tb group by AA,BB order by 1' exec(@sql) /* AA A B C ----------- ---- ---- ---- 1 a a - 1 b - b 2 - a a */