易截截图软件、单文件、免安装、纯绿色、仅160KB

通过两个例子讲解PIVOT/UNPIVOT的用法_SQL技巧

使用过SQL Server 2000的人都知道,要想实现行列转换,必须综合利用聚合函数和动态SQL,具体实现起来需要一定的技巧,而在SQL Server 2005中,使用新引进的关键字PIVOT/UNPIVOT,则可以很容易的实现行列转换的需求。
在本文中我们将通过两个简单的例子详细讲解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
----------- ----------- ----


相关文档:

sql 备忘

**************************************
****     sql  查询备忘                                   &nb ......

探讨SQL语句技巧 优化DB2应用程序性能

本文以IBM的关系数据库管理系统DB2 Universal Database(通用数据库) 版本7.1为背景,与大家共同探讨编写好的SQL语句的技巧,以求DB2应用程序以求DB2应用程序获得更优的性能。
  当我们设计一个新的或分析一个现存的系统时,其中所要考虑的一个重要问题就是应用程序的设计问题。即使数据库设计得很好而且还经过优化处理, ......

SQL优化

SQL优化34条
我们要做到不但会写SQL,还要做到写出性能优良的SQL,以下为笔者学习、摘录、并汇总部分资料与大家分享!
(1)      选择最有效率的表名顺序(只在基于规则的优化器中有效):
ORACLE 的解析器按照从右到左的顺序处理from子句中的表名,from子句中写在最后的表(基础表 driving tabl ......

sql 常用

公司组织SQL水平考试,看了写教材,写了点总结发上来跟大家分享。
我公司使用的是Sybase ASE12.5,所以下面的一些特性是针对Sybase ASE的。
一:SQL Bisic
1:SQL(Structured Quary Language)特性:
a:标准化
b:非过程化的
c:可优化的
d:面向集合操作的
2:ASE中的数据类型
a:Numberic
b:Character
c:Dat ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号