首页 »数据库 » pivot:通过两个例子讲解PIVOT/UNPIVOT的用法 »正文
pivot:通过两个例子讲解PIVOT/UNPIVOT的用法
来源: 发布时间:星期四, 2008年12月11日 浏览:16次 评论:0
="t18">使用过SQL Server 2000 ![](/icons/5206de.gif) 人都知道 ![](/icons/5206dou.gif) 要想实现行列转换,必须综合利用聚合 ![](/icons/5206hanshu.gif) 和动态SQL ![](/icons/5206dou.gif) 具体实现起来需要 ![](/icons/5206yi.gif) 定 ![](/icons/5206de.gif) 技巧 ![](/icons/5206dou.gif) 而在SQL Server 2005中 ![](/icons/5206dou.gif) 使用新引进 ![](/icons/5206de.gif) 关键字PIVOT/UNPIVOT ![](/icons/5206dou.gif) 则可以很容易 ![](/icons/5206de.gif) 实现行列转换 ![](/icons/5206de.gif) 需求
在本文中我们将通过两个简单 例子详细讲解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)
相关文章
读者评论
发表评论
|
|