ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 竖表转横表

竖表转横表

原创 Linux操作系统 作者:virgoboy20 时间:2010-04-19 17:10:08 0 删除 编辑

把以下表的数据转成横项的
  A1 A2 A3 A4 A5
2006级期末考 20080101 张三 语文 101
2006级期末考 20080202 李四 语文 109
2006级期末考 20080303 王五 语文 100
2006级期末考 20080101 张三 数学 101
2006级期末考 20080202 李四 数学 85
2006级期末考 20080303 王五 数学 58
2006级期末考 20080101 张三 政治 56
2006级期末考 20080202 李四 政治 56
2006级期末考 20080303 王五 政治 50

我想把以上的表转成
    
  考试项目    学号    姓名 语文 数学 政治
    
2006级期末考 20080101 张三 101  101  56
2006级期末考 20080202 李四 109  85   56
2006级期末考 20080303 王五 100  58   50

但注意的是科目是不固定的也就是说如果他再增加科目的时候而横项也会自动增加  

例如,如果加了英语

     A1        A2     A3   A4   A5

2006级期末考 20080101 张三 语文 101
2006级期末考 20080202 李四 语文 109
2006级期末考 20080303 王五 语文 100
2006级期末考 20080101 张三 数学 101
2006级期末考 20080202 李四 数学 85
2006级期末考 20080303 王五 数学 58
2006级期末考 20080101 张三 政治 56
2006级期末考 20080202 李四 政治 56
2006级期末考 20080303 王五 政治 50
2006级期末考 20080101 张三 英语 102
2006级期末考 20080202 李四 英语 110
2006级期末考 20080303 王五 英语 93

那么就应该变为

  考试项目     学号   姓名 语文 数学 政治 英语
    
2006级期末考 20080101 张三 101  101  56   102
2006级期末考 20080202 李四 109  85   56   110
2006级期末考 20080303 王五 100  58   50   93

解决:
--建立测试环境 set nocount on
create table test(A1 varchar(20),A2 varchar(20),A3 varchar(20),A4 varchar(20),A5 float)
insert into test select '2006级期末考','20080101','张三','语文','101' insert into test select '2006级期末考','20080202','李四','语文','109' insert into test select '2006级期末考','20080303','王五','语文','100' insert into test select '2006级期末考','20080101','张三','数学','101' insert into test select '2006级期末考','20080202','李四','数学','85' insert into test select '2006级期末考','20080303','王五','数学','58' insert into test select '2006级期末考','20080101','张三','政治','56' insert into test select '2006级期末考','20080202','李四','政治','56' insert into test select '2006级期末考','20080303','王五','政治','50' insert into test select '2006级期末考','20080101','张三','英语','102' insert into test select '2006级期末考','20080202','李四','英语','110' insert into test select '2006级期末考','20080303','王五','英语','93' go --测试 declare @sql varchar(8000) set @sql='select A1,A2,A3' select @sql=@sql+',sum(case when A4='''+A4+''' then A5 else 0 end)['+A4+']' from (select distinct A4 from test)a set @sql=@sql+' from test group by A1,A2,A3 order by A1,A2,A3' exec(@sql) --删除测试环境 drop table test set nocount off /*-- A1 A2 A3 数学 英语 语文 政治 -------------------- -------------------- -------------------- ---------------------- ---------------------- ---------------------- ---------------------- 2006级期末考 20080101 张三 101 102 101 56 2006级期末考 20080202 李四 85 110 109 56 2006级期末考 20080303 王五 58 93 100 50 */


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/8780503/viewspace-660163/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 没有了~
下一篇: ITPUB BLOG
请登录后发表评论 登录
全部评论

注册时间:2010-04-19

  • 博文量
    17
  • 访问量
    34468