行列转换等经典sql语句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 **, --创建列id,并且每次新增一条记录就会加1 name varchar(50), subject varchar(50), result int, primary key (id) --定义id为表cj的主键 );--truncate table cj--select * from cjinsert into cjselect '张三','语文',80 union all select '张三','数学',90 union allselect '张三','物理',85 union allselect '李四','语文',85 union allselect '李四','物理',82 union allselect '李四','英语',90 union allselect '李四','**',70 union allselect '王五','英语',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 d**tinct subject from cj) as cj --把所有唯一的科目的名称都列举出来select @sql = @sql+' from cj group by name'exec (@sql)2. 行列转换--合并原表: 班级 学号 1 1 1 2 1 3 2 1 2 2 3 1转换后的表: 班级 学号 1 1,2,3 2 1,2 3 1 实例:create table classno --创建表classno( id int identity(1,1) not **, --创建列id,并且每次新增一条记录就会加1 class varchar(50), --班级列 number varchar(50), --学号列 primary key(id) --定义id为表classno的主键);--truncate table classno--select * from classnoinsert into classnoselect 1,1 union allselect 1,2 union allselect 1,3 union allselect 2,1 union allselect 2,2 union allselect 3,1创建一个合并的函数--drop function kfreturncreate function kfreturn(@class varchar(50))returns varchar(8000)as begindeclare @str varchar(8000)set @str = ''select @str = @str + cast(number as varchar(50)) + ',' from classno where class = @class set @str = substring(@str,1,len(@str)-1)return(@str)end--调用自定义函数得到结果select d**tinct class,dbo.kfreturn(class) from classno3:列转行--drop table columntorowcreate table columntorow( id int identity(1,1) not **, --创建列id,并且每次新增一条记录就会加1 a int, b int, c int, d int, e int, f int, g int, h int, primary key(id) --定义id为表columntorow的主键 );--truncate table columntorow --select * from columntorowinsert into columntorow select 15,9,1,0,1,2,4,2 union allselect 22,34,44,5,6,7,8,7 union allselect 33,44,55,66,77,88,99,12declare @sql varchar(8000)set @sql = ''select @sql = @sql + rtrim(name) + ' from columntorow union all select ' from syscolumns where id = object_id('columntorow')set @sql = substring(@sql,1,len(@sql)-70)--70的长度就是这个字符串'from columntorow union all select id from columntorow union all select ',因为它会把id这一列的值也算进去,所以要把它截掉exec ('select ' + @sql + ' from columntorow') 20210311