Matthewl 发表于 2018-10-23 09:42:58

SQL行列互换很方便

  ---行转列--pivot
  create table tempTable
  (

  id int primary key>  Student nvarchar(36),
   nvarchar(36),
  Score int,
  )
  select * from tempTable
  insert into tempTable values ('张三','语文','90')
  insert into tempTable values ('张三','语文','89')
  insert into tempTable values ('李四','语文','90')
  insert into tempTable values ('王五','语文','93')
  insert into tempTable values ('张三','数学','89')
  insert into tempTable values ('李四','数学','79')
  insert into tempTable values ('王五','数学','88')
  insert into tempTable values ('张三','英语','87')
  insert into tempTable values ('李四','英语','94')
  insert into tempTable values ('王五','英语','96')
  select Student,sum(语文)as 语文,sum(数学) as 数学,sum(英语) as 英语into tempsubject from tempTable pivot(avg(Score) for in (语文,数学,英语)) as A group by Student order by 语文 desc
  ---列转行unpivot
  select * from tempsubject
  unpivot
  (
  Score for in(语文,数学,英语)
  )
  as f

页: [1]
查看完整版本: SQL行列互换很方便