简体   繁体   中英

How to insert data from 2 other tables in oracle

I'm making a new table. The value/data in the table are taken from another table. for example: in table A I have field Code with 2 data, EXE and IMP . In table B I have field Year with data 2016 and 2017 . Now i need to make table C with field Status where the data in field Status are EXE-2016 , IMP-2016 , EXE-2017 and IMP-2017 . How was the query for this kind of problem?

table A
code | code_name | flag
EXE | Execute | Y
IMP | Implement| Y

table B
Year | phase | flag
2016 | P1 | Y
2016 | P2 | Y
2017 | P1 | Y
2017 | P2 | Y
2018 | P1 | N

table C
Status | Flag
EXE-2016 | Y
IMP-2016 | Y
EXE-2017 | Y
IMP-2017 | Y
EXE-2018 | N
IMP-2018 | N

In your case, it's better to create a view in such a way to record sql for later usage like a table :

create view tableC as
select code||' - '||year status, flag
from (
       select a.code, b.year, b.flag  from tableA a cross join tableB b       
     )
group by code, year, flag     
order by year, code;/

select * from tableC;/

D emo

You want to cross join records from two tables:

  • each record from table A
  • each year from table B with its MAX flag (ie 'Y' wins over 'N')

Then use CREATE TABLE c AS <query> in order to create a table C from the query result.

create table c as
select a.code || '-' || bb.year as status, bb.flag
from a
cross join
(
  select year, max(flag) as flag
  from b
  group by year
) bb;

(And maybe Barbaros Özhan is right and you actually want to create a view instead. Then use create view c as <query> .)

create table C as
select A.code || '-' || B.year as status
from A, B
CREATE table C as 
SELECT A.Code || '-' || B.Year AS 
STATUS , B.flag
FROM A,B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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