行列互轉

定義:

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


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