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

谈SQL Server 2005中的T SQL增强E


新的关系运算符 PIVOT/UNPIVOT/APPLY
1、PIVOT
PIVOT运算符将行旋转为列,并且可能同时执行聚合。使用PIVOT运算符时要注意的重要一点是,需要为它提供一个查询表达式,表达式使用视图、派生表或者是CTE只返回所关注的列。
2、UNPIVOT
UNPIVOT运算符执行与PIVOT运算符相反的操作;他将列旋转为行了。
3、APPLY
APPLY关系运算符允许您对外部表的每个行调用指定的表值函数一次。您可以在查询的from子句中指定APPLY,其方式与使用JOIN关系运算符类似。APPLY具有两种形式:CROSS APPLY和OUTER APPLY。
演示:
USE demo
GO
CREATE TABLE orders
(
Customer VARCHAR(10) NOT NULL,
product VARCHAR(20) NOT NULL,
quantity INT NOT NULL
)
GO
INSERT orders VALUES('Mike', 'Bike',3)
INSERT orders VALUES('Mike','Chain',2)
INSERT orders VALUES('Mike','Bike',5)
INSERT orders VALUES('Lisa','Bike',3)
INSERT orders VALUES('Lisa','Chain',3)
INSERT orders VALUES('Lisa','Chain',4)
INSERT orders VALUES('Lisa','Bike',2)
SELECT * from orders
SELECT * from orders
PIVOT (SUM(quantity) FOR product IN ([Bike],[Chain])) AS a
USE demo
GO
CREATE TABLE SALES1
(
[Year] INT,
Quarter CHAR(2),
Amount FLOAT
)
GO
INSERT INTO SALES1 VALUES (2001, 'Q1', 80)
INSERT INTO SALES1 VALUES (2001, 'Q2', 70)
INSERT INTO SALES1 VALUES (2001, 'Q3', 55)
INSERT INTO SALES1 VALUES (2001, 'Q3', 110)
INSERT INTO SALES1 VALUES (2001, 'Q4', 90)
INSERT INTO SALES1 VALUES (2002, 'Q1', 200)
INSERT INTO SALES1 VALUES (2002, 'Q2', 150)
INSERT INTO SALES1 VALUES (2002, 'Q2', 40)
INSERT INTO SALES1 VALUES (2002, 'Q2', 60)
INSERT INTO SALES1 VALUES (2002, 'Q3', 120)
INSERT INTO SALES1 VALUES (2002, 'Q3', 110)
INSERT INTO SALES1 VALUES (2002, 'Q4', 180)
GO
SELECT * from SALES1
PIVOT
(SUM (Amount) --使用SUM聚合数量列
FOR [Quarter] --PIVOT Quarter 列
IN (Q1, Q2, Q3, Q4)) --使用季节
AS P
GO
SELECT * INTO temp1 from orders
PIVOT (sum(quantity) FOR product IN ([Bike],[Chain])) AS a
SELECT * from temp1
SELECT customer, product,quantity
from temp1
UNPIVOT(quantity FOR product IN ([Bike],[Chain])) AS a
----------------


相关文档:

航空公司管理系统(VC++ 与SQL 2005)

系统环境:Windows 7
软件环境:Visual C++ 2008 SP1 +SQL Server 2005
本次目的:编写一个航空管理系统
      这是数据库课程设计的成果,虽然成绩不佳,但是作为我用VC++ 以来编写的最大程序还是传到网上,以供参考。用VC++ 做数据库设计并不容易,但也不是不可能。以下是我的程序界面,后面 ......

oracle中比较实用sql语句

-- 查看ORACLE 数据库中本用户下的所有表
SELECT table_name from user_tables;
-- 查看ORACLE 数据库中所有用户下的所有表
select user,table_name from all_tables;
-- 查看ORACLE 数据库中本用户下的所有列
select table_name,column_name from user_tab_columns;
-- 查看ORACLE 数据库中本用户下的所有列
se ......

Oracle SQL实例

1。select * from a where a.rowid=(select min(b.rowid) from b where a.id=b.id);
create test1(
nflowid number primary key, 
ndocid number,
drecvdate date);
insert into test1 values (1, 12301, sysdate) ;
insert into test1 values (2, 12301, sysdate);
select * from test1 order by drecvdate:
......

SQL语句坚行转横列的一种方法

库位  货物编号 库存数
1     0101     50
1     0102     60
1     0103     50
2     0101     90
2     0103     100
2     0111     30
3     0101     12 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号