Oracle 中的Pivoting Insert用法

1.标准Insert --单表单行插入

  语法:
  INSERT INTO table [(column1,column2,...)] VALUE (value1,value2,...)
 
  例子:
  insert into dep (dep_id,dep_name) values(1,'技术部');
  
  备注:使用标准语法只能插入一条数据,且只能在一张表中插入数据
 
2, 无条件 Insert all --多表多行插入
 
   语法:
INSERT [ALL] [condition_insert_clause]
[insert_into_clause values_clause] (subquery)
 
   示例:
INSERT ALL
INTO sal_history(emp_id,hire_date,salary) values (empid,hiredate,sal)
INTO mgr_history(emp_id,manager_id,salary) values (empid,hiredate,sal)
SELECT employee_id empid,hire_date hiredate,salary sal,manager_id mgr
FROM employees
WHERE employee_id>200;
 
3,有条件的Insert
    语法:
INSERT [ALL | FIRST]
WHEN condition THEN insert_into_clause values_clause
[WHEN condition THEN] [insert_into_clause values_clause]
......
[ELSE] [insert_into_clause values_clause] 
Subquery;
 
    示例:
Insert All
when id>5 then into z_test1(id, name) values(id,name)
when id<>2 then into z_test2(id) values(id)
else into z_test3 values(name)
select id,name from z_test;
 
当使用ALL关键字时,oracle会从上至下判断每一个条件,当条件满足时就执行后面的into语句
在上面的例子中,如果ID=6 那么将会在z_test1中插入一条记录,同时也在z_test2中插入一条记录
    备注:
      当使用FIRST关键字时,oracle会从上至下判断每一个条件,当遇到第一个满足时就执行后面的into语句,
      同时中断判断的条件判断,在上面的例子中,如果ID=6,仅仅会在z_test1中插入一条数据
 
4, 旋转Insert (pivoting insert)
create table sales_source_data (
employee_id number(6),
week_id number(2),
sales_mon number(8,2),
sales_tue number(8,2),
sales_wed number(8,2),
sales_thur number(8,2),
sales_fri number(8,2)
);
insert into sales_source_data values (176,6,2000,3000,4000,5000,6000);
SQL> select * from sales_source_data;
EMPLOYEE_ID WEEK_ID  SALES_MON  SALES_TUE  SALES_WED SALES_THUR  SALES_FRI
----------- ------- ---------- ---------- ---------- ---------- ----------
        176       6    2000.00    3000.00    4000.00    5000.00    6000.00
create table sales_info (
employee_id number(6),
week number(2),
sales number(8,2)
);
看上面的表结构,现在将要sales_source_data表中的数据转换到sales_info表中,这种情况就需要使用旋转Insert
 
示例如下:
insert all
into sales_info values(employee_id,week_id,sales_mon)
into sales_info values(employee_id,week_id,sales_tue)
into sales_info values(employee_id,week_id,sales_wed)
into sales_info values(employee_id,week_id,sales_thur)
into sales_info values(employee_id,week_id,sales_fri)
select employee_id,week_id,sales_mon,sales_tue,
sales_wed,sales_thur,sales_fri
from sales_source_data;
SQL> select * from sales_infor;
EMPLYEE_ID WEEK      SALES
---------- ---- ----------
       176    6    2000.00
       176    6    3000.00
       176    6    4000.00
       176    6    5000.00
       176    6    6000.00

SQL> 
从该例子可以看出,所谓旋转Insert是无条件 insert all 的一种特殊应用,但这种应用被oracle官方,赋予了一个pivoting insert的名称,即旋转insert
《FROM:http://www.cnblogs.com/einyboy/archive/2012/08/06/2624886.html
 

posted on 2015-06-25 12:03  遠離塵世の方舟  阅读(562)  评论(0编辑  收藏  举报

导航