pivot用法

来源:互联网 发布:mac java开发必备软件 编辑:程序博客网 时间:2024/05/23 07:25
declare @tb table
(id int primary key identity(1,1),
 name nvarchar(50),
 课目 nvarchar(2),
 分数 decimal(10,2)
)
insert into @tb
   select '张三','语文',80
   union all
   select '张三','英语',95
   union all
   select '李四','语文',85
   union all  
   select '李四','英语',93
   union all  
   select '李四','数学',80
   union all
   select '张三','数学',90
---pivot 用法
select * from (select name,课目,分数 from @tb) a pivot
      (sum(分数) for 课目 in (语文,数学,英语)) b
---pivot 加汇总行
select *,分数=语文+数学+英语 from (select name,课目,分数 from @tb) a pivot
      (sum(分数) for 课目 in (语文,数学,英语)) b
----unpivot 用法
;with china as
(
select * from (select name,课目,分数 from @tb) a pivot
      (sum(分数) for 课目 in (语文,数学,英语)) b
)
select * from china a
 unpivot (分数 for 课目  in (语文,数学,英语))b
原创粉丝点击