行列置换:
- 姓名 语文 数学 物理
- ----------------------------------
- 张三 80 90 85
- 李四 85 92 82
- 要求使用T-SQL语言实现以下结果:
- 课程 张三 李四
- ----------------------
- 语文 80 85
- 数学 90 92
- 物理 85 82
- drop table sc
- create table sc(姓名 varchar(10),语文 int,数学 int,物理 int)
- insert into sc
- select ‘张三‘,80,90,85
- union all
- select ‘李四‘,85,92,82
- select * from sc
- -------------这个过程不就是unpivot,有时间再补充?
- select * into sc1 from(
- select 姓名,‘语文‘ 课程,语文 分数 from sc
- union
- select 姓名,‘数学‘ 课程,数学 from sc
- union
- select 姓名,‘物理‘ 课程,物理 from sc
- )t
- 补充unpivot,和上面操作时同样的效果
- select 姓名,课程,分数 into #sc1 from sc unpivot(分数 for 课程 in([语文],[数学],[物理]))a
- declare @sql varchar(8000)
- set @sql=‘select ‘
- select @sql=@sql+‘, max(case when 姓名=‘‘‘+姓名+‘‘‘ then 分数 else ‘‘‘‘end)[‘+姓名+‘]‘ from (select distinct 姓名 from
- sc1)t
- set @sql=stuff(@sql,8,1,‘‘)
- set @sql=@sql+‘ ,课程 from sc1 group by 课程‘
- print @sql
- exec(@sql)
- 补充动态pivot和unpiot
- --------------pivot
- declare @sql varchar(8000)
- select @sql = isnull(@sql + ‘],[‘ , ‘‘) + 课程 from tb group by 课程
- print @sql
- set @sql = ‘[‘ + @sql + ‘]‘
- exec (‘select * from (select * from tb) a pivot (max(分数) for 课程 in (‘ + @sql + ‘)) b‘)
- --------------unpivot
- declare @sql varchar(8000)
- select @sql = isnull(@sql + ‘],[‘ , ‘‘) + name from syscolumns where id=OBJECT_ID(‘tb‘) and colorder>1
- set @sql = ‘[‘ + @sql + ‘]‘
- exec (‘select 姓名,课程,分数 from (select * from tbtb) a unpivot (分数 for 课程 in (‘ + @sql + ‘)) b‘)
sql server行列转化和行列置换
标签:oat 动态 -- print tab unp object_id for tar