1.--行列转换 原表: 姓名 科目 成绩 张三 语文 80 张三 数学 90 张三 物理 85 李四 语文 85 李四 物理 82 李四 英语 90 李四 政治 70 王五 英语 90
转换后的表: 姓名 数学 物理 英语 语文 政治 李四 0 82 90 85 70 王五 0 0 90 0 0 张三 90 85 0 80 0
实例: create table cj --创建表cj ( ID Int IDENTITY (1,1) not null, --创建列ID,并且每次新增一条记录就会加1 Name Varchar(50), Subject Varchar(50), Result Int, primary key (ID) --定义ID为表cj的主键 ); --Truncate table cj --Select * from cj Insert into cj Select '张三','语文',80 union all Select '张三','数学',90 union all Select '张三','物理',85 union all Select '李四','语文',85 union all Select '李四','物理',82 union all Select '李四','英语',90 union all Select '李四','政治',70 union all Select '王五','英语',90 --行列转换 Declare @sql varchar(8000) Set @sql = 'Select Name as 姓名' Select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result else 0 end) ['+Subject+']' from (select distinct Subject from cj) as cj --把所有唯一的科目的名称都列举出来 Select @sql = @sql+' from cj group by name' Exec (@sql)
|
列行转换:
Create Table t_errect
(P_nameVarchar(10),
m1Int,
m2Int,
m3Int)
Insert t_errect Select 'pc1', 3, 5, 8
Union All Select 'pc2', 6, 9, 12
GO
declare @m_str varchar(50),@monthly int,@sql varchar(2000)
select @monthly=1, @sql = ''
while (@monthly<4)
begin
set @m_str='m'+cast(@monthly as varchar(5))
set @sql= @sql + ' union all select P_name,'''+ @m_str+''' as monthly,'+@m_str+' as m_value from t_errect'
set @monthly=@monthly+1
end
select @sql = Stuff(@sql, 1, 10, '')
exec(@sql)
GO
Drop Table t_errect
--Result
/*
P_namemonthlym_value
pc1m13
pc2m16
pc1m25
pc2m29
pc1m38
pc2m312
*/