行列互转

定义:

Pivot英文意思:回转运动

PIVOT用于将列值旋转为列名(即行转列),

UNPIVOT用于将列名转为列值(即列转行),

也可以在SQL Server 2000可以用聚合函数配合CASE语句实现

语法:

PIVOTUNPIVOT的语法区别在于是否有使用聚合函数

PIVOT

table_source
PIVOT(
聚合函数(value_column)
FOR pivot_column
IN(<column_list>)
)

UNPIVOT

table_source
UNPIVOT(
value_column
FOR pivot_column
IN(<column_list>)
)

注意:

PIVOT、UNPIVOT是SQL Server 2005 的语法

实例:

一、行转列

1、建立表格

if object_id('test')is not null drop table test
go
create table test(姓名 varchar(10),课程 varchar(10),分数 int)
insert into test values('张三','语文',65)
insert into test values('张三','数学',85)
insert into test values('张三','英语',70)
insert into test values('李四','语文',80)
insert into test values('李四','数学',71)
insert into test values('李四','英语',83)
go
select * from test

姓名         课程         分数

---------- ---------- -----------

张三         语文         65

张三         数学         85

张三         英语         70

李四         语文         80

李四         数学         71

李四         英语         83

1)、通过聚合函数配合CASE语句实现

select 姓名,
 max(case 课程 when '语文' then 分数 else 0 end)语文,
 max(case 课程 when '数学' then 分数 else 0 end)数学,
 max(case 课程 when '英语' then 分数 else 0 end)英语
from test
group by 姓名

(2)、通过pivot实现:

select * from test pivot(max(分数) for 课程 in (语文,数学,英语))p

得到的结果一致:

姓名         语文          数学          英语

---------- ----------- ----------- -----------

李四         80          71          83

张三         65          85          70

 

二、列转行

1、建立表格

if object_id('test')is not null drop table test
go
create table test(姓名 varchar(10),语文 int,数学 int,英语 int)
insert into test values('张三',65,85,70)
insert into test values('李四',80,71,83)
go
select * from test

姓名         语文          数学          英语

---------- ----------- ----------- -----------

张三         65          85          70

李四         80          71          83

(1)、通过聚合函数配合CASE语句实现

select * from
(
 select 姓名,课程='语文',分数=语文 from test
 union all
 select 姓名,课程='数学',分数=数学 from test
 union all
 select 姓名,课程='物理',分数=英语 from test
) p
order by 姓名,case 课程 when '语文' then 1 when '数学' then 2 when '英语' then 3 end

姓名         课程   分数

---------- ---- -----------

李四         物理   83

李四         语文   80

李四         数学   71

张三         物理   70

张三         语文   65

张三         数学   85

(2)、通过pivot实现:

select 姓名,课程,分数 from test unpivot (分数 for 课程 in ([语文],[数学],[英语])) p

姓名         课程   分数

---------- ---- -----------

李四         物理   83

李四         语文   80

李四         数学   71

张三         物理   70

张三         语文   65

张三         数学   85


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章