列轉換行 IF OBJECT_ID('tb') IS NOT NULL DROP TABLE tb go CREATE TABLE tb(姓名 VARCHAR(10),語文 INT,數學 INT,物理 INT) INSERT INTO tb VALUES('張三',74,83,93) INSERT INTO tb VALUES('李四',74,84,94) go SELECT * FROM tb 動態寫法 declare @sql varchar(8000) select @sql=isnull(@sql+' union all ','')+' select 姓名, [課程]=' +quotename(Name,'''')+' , [分數] = '+quotename(Name)+' from tb' from syscolumns where Name!='姓名'and ID=object_id('tb')--表名tb,不包含列名為姓名的其他列 order by colid exec(@sql+' order by 姓名') 靜態寫法 select * from ( select 姓名,課程='語文',分數=語文 from tb union all select 姓名,課程='數學',分數=數學 from tb union all select 姓名,課程='物理',分數=物理 from tb )t order by 姓名,case 課程 when'語文'then 1 when'數學' then 2 when '物理'then 3 end 行轉列 CREATE TABLE tb1(姓名 VARCHAR(10),課程 VARCHAR(10),分數 INT) insert into tb1 VALUES ('張三','語文',74) insert into tb1 VALUES ('張三','數學',83) insert into tb1 VALUES ('張三','物理',93) insert into tb1 VALUES ('李四','語文',74) insert into tb1 VALUES ('李四','數學',84) insert into tb1 VALUES ('李四','物理',94) 固定寫法 SELECT * FROM tb1 pivot( MAX(分數) FOR 課程 IN (語文,數學,物理))a 動態寫法 --SQL SERVER 2000動態SQL,指課程不止語文、數學、物理這三門課程。(以下同) --變量按sql語言順序賦值 declare @sql varchar(500) set @sql='select 姓名' select @sql=@sql+' , max(case 課程 when '''+課程+''' then 分數 else 0 end)['+課程+']' from(select distinct 課程 from tb1)a--同from tb group by課程,默認按課程名排序 set @sql=@sql+' from tb1 group by 姓名' exec(@sql) --使用isnull(),變量先確定動態部分 declare @sql varchar(8000) select @sql=isnull(@sql+',','')+' max(case 課程 when '''+課程+''' then 分數 else 0 end) ['+課程+']' from(select distinct 課程 from tb1)as a set @sql='select 姓名,'+@sql+' from tb1 group by 姓名' exec(@sql)