日期:2014-05-17 浏览次数:20591 次
create table #tb(db_element varchar(10),att_name varchar(10),att_value int)
insert into #tb
select '张三','a',74 union all
select '张三','b',83 union all
select '张三','c',93 union all
select '李四','a',74 union all
select '李四','b',84 union all
select '李四','c',94
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+','+att_name from #tb group by att_name
set @sql=stuff(@sql,1,1,'')
set @sql='select * from #tb pivot (max(att_value) for att_name in ('+@sql+')) a'
exec(@sql)
drop table #tb
----------------------------------
de_element a b c
李四 74 84 94
张三 74 83 93
---------------------
(6 行受影响)
(2 行受影响)
------解决方案--------------------
declare @sql varchar(1000)
set @sql='select db_element'
select @sql=@sql+',max(case when '''+att_name+''' then att_value else null end ['+att_name+']'
from(select distinct att_name from tb)a
set @sql=@sql+' from tb group by db_element'
exec(@sql)