PIVOT UNPIVOT的用法 行列轉換

2021-05-22 06:10:35 字數 1992 閱讀 4393

--pivot/unpivot的用法(行列轉換)

--pivot的用法:

--首先建立測試表,然後插入測試資料

create table test(id int,name varchar(20),quarter int,profile int)

insert into test values(1,'a',1,1000)

insert into test values(1,'a',2,2000)

insert into test values(1,'a',3,4000)

insert into test values(1,'a',4,5000)

insert into test values(2,'b',1,3000)

insert into test values(2,'b',2,3500)

insert into test values(2,'b',3,4200)

insert into test values(2,'b',4,5500)

select * from test

--id name quarter profile

--1 a 1 1000

--1 a 2 2000

--1 a 3 4000

--1 a 4 5000

--2 b 1 3000

--2 b 2 3500

--2 b 3 4200

--2 b 4 5500

--(8 row(s) affected)

--使用pivot將四個季度的利潤轉換成橫向顯示:

select id,name,

[1] as "一季度",

[2] as "二季度",

[3] as "三季度",

[4] as "四季度"

from

test

pivot

sum(profile)

for quarter in

([1],[2],[3],[4])

as pvt

--id name 一季度 二季度 三季度 四季度

--1 a 1000 2000 4000 5000

--2 b 3000 3500 4200 5500

--(2 row(s) affected)

--unpivot的用法:

--首先建立測試表,然後插入測試資料

drop table test

create table test(id int,name varchar(20), q1 int, q2 int, q3 int, q4 int)

insert into test values(1,'a',1000,2000,4000,5000)

insert into test values(2,'b',3000,3500,4200,5500)

select * from test

--id name q1 q2 q3 q4

--1 a 1000 2000 4000 5000

--2 b 3000 3500 4200 5500

--(2 row(s) affected)

--使用unpivot,將同一行中四個季度的列資料轉換成四行資料:

select id,name,quarter,profile

from

test

unpivot

profile

for quarter in

([q1],[q2],[q3],[q4])

as unpvt

--id name quarter profile

--1 a q1 1000

--1 a q2 2000

--1 a q3 4000

--1 a q4 5000

--2 b q1 3000

--2 b q2 3500

--2 b q3 4200

--2 b q4 5500

--(8 row(s) affected)

SQL通過PIVOT UNPIVOT實現行列轉換

在sqlserver 2005中,使用關鍵字pivot unpivot,可以很容易的實現行列轉換的需求。現在將通過兩個簡單的例子詳細講解pivot unpivot的用法。一 pivot的用法 首先建立測試表,然後插入測試資料 create table test id int,name varchar...

dict的用法 while True的用法

d 直接傳入字典 dict 建立空字典 dict a a b b t t 傳入關鍵字 dict zip one two three 1,2,3 對映函式方式來構造字典 dict one 1 two 2 three 3 可迭代物件方式來構造字典 d.values 只獲取字典中的值 d.keys 只獲取...

undef的用法 undef的用法

define test a 1 define test class a clase t1 include test.h undef test a undef test class a 在這乙個檔案中使用巨集定義 define test a 1 define test class a clase t1...