create table A ( col1 varchar(10), col2 int, col3 int )insert A select '77', 8350, 34 union select '78', 8350, 12 union select '77', 8810, 34 union select '78', 8810, 45 go--查询 declare @sql varchar(1000) set @sql='' select @sql=@sql+',max(case when col1='''+col1+''' then col3 else null end) as '''+col1+'''' from A group by col1 select @sql='select col2'+@sql+' from A group by col2' exec(@sql)--删除测试环境 drop table A--结果 /* col2 77 78 ----------- ----------- ----------- 8350 34 12 8810 34 45 */
(
col1 varchar(10),
col2 int,
col3 int
)insert A
select '77', 8350, 34 union
select '78', 8350, 12 union
select '77', 8810, 34 union
select '78', 8810, 45
go--查询
declare @sql varchar(1000)
set @sql=''
select @sql=@sql+',max(case when col1='''+col1+''' then col3 else null end) as '''+col1+''''
from A group by col1
select @sql='select col2'+@sql+' from A group by col2'
exec(@sql)--删除测试环境
drop table A--结果
/*
col2 77 78
----------- ----------- -----------
8350 34 12
8810 34 45
*/