专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »数据库 » pivot:通过两个例子讲解PIVOT/UNPIVOT的用法 »正文

pivot:通过两个例子讲解PIVOT/UNPIVOT的用法

来源: 发布时间:星期四, 2008年12月11日 浏览:16次 评论:0
="t18">使用过SQL Server 2000人都知道要想实现行列转换,必须综合利用聚合和动态SQL具体实现起来需要技巧而在SQL Server 2005中使用新引进关键字PIVOT/UNPIVOT则可以很容易实现行列转换需求

在本文中我们将通过两个简单例子详细讲解PIVOT/UNPIVOT用法

PIVOT用法:

首先创建测试表然后插入测试数据

=code style="FONT-SIZE: 9pt" bgColor=#e6e6e6>
create table test(id ,name varchar(20),quarter ,profile ) 
insert o test values(1,'a',1,1000)
insert o test values(1,'a',2,2000)
insert o test values(1,'a',3,4000)
insert o test values(1,'a',4,5000)
insert o test values(2,'b',1,3000)
insert o test values(2,'b',2,3500)
insert o test values(2,'b',3,4200)
insert o 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用法:

=code style="FONT-SIZE: 9pt" bgColor=#e6e6e6>
首先建立测试表然后插入测试数据

drop table test

create table test(id ,name varchar(20), Q1 , Q2 , Q3 , Q4 )

insert o test values(1,'a',1000,2000,4000,5000)
insert o 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)

相关文章

读者评论

  • 共0条 分0页

发表评论

  • 昵称:
  • 内容: