易截截图软件、单文件、免安装、纯绿色、仅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
----------- ----------- ----


相关文档:

VC使用SQLDMO操作SQL Server

BOOL StartServer()
{
    if(FAILED(CoInitialize(NULL)))
    {
        AfxMessageBox(_T("Com初始化失败"));
        return FALSE;
    }
    _SQLServerPtr spSQLServer ......

SQL Server 完美SPLIT函数


--
SQL Server Split函数
--
Author:zc_0101 
--
说明:
--
支持分割符多字节
--
使用方法 
--
Select * from DBO.F_SQLSERVER_SPLIT('1203401230105045','0')    
--
select * from DBO.F_SQLSERVER_SPLIT('abc1234a12348991234',' ......

sql 备忘

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

sql server 索引

sql server 创建索引
http://54laobaixing.blog.163.com/blog/static/57843681200952411133121/
SQL SERVER索引,优化
http://tieba.baidu.com/f?kz=170889655
Sybase SQL Server索引的使用和优化
http://www.yesky.com/79/211079.shtml ......

SQL Server CONVERT() 函数

原文出处:http://www.dingos.cn/index.php?topic=1874.0
定义和用法
CONVERT() 函数是把日期转换为新数据类型的通用函数。
CONVERT() 函数可以用不同的格式显示日期/时间数据
语法
CONVERT(data_type(length),data_to_be_converted,style)
data_type(length) 规定目标数据类型(带有可选的长度)。data_to_be_conve ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号