简体   繁体   English

从Oracle 11g中的现有表创建新表

[英]CREATE New Table from existing tables in Oracle 11g

I have 2 tables that doesn't have primary keys. 我有2个没有主键的表。 These 2 tables have same number of rows. 这两个表具有相同的行数。 I want to create a new table from getting some columns from table1 and some columns from table 2. I want to combine first row from table1 and first row from table2. 我想通过获取来自table1的某些列和来自表2的某些列来创建一个新表。我想合并来自table1的第一行和来自table2的第一行。 Below is example 以下是示例

TABLE1 表格1

ACOL1 ACOL2 ACOL3
A1 A2 A3
B1 B2 B3
C1 C2 C3

TABLE2 表2

BCOL1 BCOL2 BCOL3
11 12 13
21 22 23
31 32 33

COMBINED_TABLE COMBINED_TABLE

ACOL1 BCOL2 BCOL3
A1 12 13
B1 22 23
C1 32 33

I tried below query but no luck. 我尝试下面的查询,但没有运气。 It gives below error: 它给出以下错误:
Query : 查询:

create table COMBINED_TABLE 
AS 
select a.ACOL1, b.BCOL2, b.BCOL3 
from (select ACOL1,rownum from TABLE1) a, 
     (select BCOL2, BCOL3, rownum from TABLE2) b 
WHERE a.rownum = b.rownum

Error : ORA-01747:"invalid user.table.column, table.column, or column specification" 错误: ORA-01747:“无效的user.table.column,table.column或列规范”

create table combined_table
as
select a.acol1, b.bcol2, b.bcol3
from (
  select acol1, row_number() over (order by acol1) as rn
  from table1
) a 
  join (
    select bcol2, bcol3, row_number() over (order by bcol1) as rn
    from table2
  ) b on a.rn = b.rn

Using row_number() is more robust than rownum as you can actually define what "last" or "first" row means (those terms don't have a meaning unless some order is defined). 使用row_number()rownum更健壮,因为您实际上可以定义“最后”或“第一”行的含义(除非定义了某些顺序,否则这些术语没有意义)。

When you define an order by in the window function the resulting join is more stable as the row numbers are always calculated the same way (which is not the case with rownum ). 当您在窗口函数中使用order by定义order by由于行号始终以相同的方式计算(结果不是 rownum ),因此生成的联接更加稳定。

You cannot use rownum as a column name, giving it an alias solves the problem 您不能将rownum用作列名,为其提供别名可以解决问题

create table COMBINED_TABLE 
AS 
select a.ACOL1, b.BCOL2, b.BCOL3 
from (select ACOL1,rownum rn from TABLE1) a, 
     (select BCOL2, BCOL3, rownum rn from TABLE2) b 
WHERE a.rn = b.rn

Try this: 尝试这个:

CREATE TABLE table1a (
  acol1 NUMBER,
  acol2 NUMBER,
  acol3 NUMBER
);

CREATE TABLE table2a (
  bcol1 NUMBER,
  bcol2 NUMBER,
  bcol3 NUMBER
);

INSERT INTO table1a VALUES (1, 2, 3);
INSERT INTO table1a VALUES (4, 5, 6);

INSERT INTO table2a VALUES (10, 20, 30);
INSERT INTO table2a VALUES (40, 50, 60);

CREATE TABLE combined_table (ct1, ct2, ct3) AS
  SELECT a.acol1, b.bcol2, b.bcol3
    FROM
      (SELECT a.*, rownum AS rn FROM table1a a) a,
      (SELECT b.*, rownum AS rn FROM table2a b) b
  WHERE a.rn = b.rn
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM