Copy oracle table data from two tables to another table - sql

Here are my tables:
create table country(
country_id number(5) primary key,
country varchar2(36)
);
create table city(
city_id number(5) primary key,
country_id number(5) constraint city_country_fk references country(country_id) NOT NULL,
city varchar2(36)
);
SQL> desc airportdemodata;
Name Null? Type
----------------------------------------- -------- ----------------------------
AIRPORT_ID NOT NULL NUMBER(5)
IATA_CODE VARCHAR2(3)
CITY VARCHAR2(36)
COUNTRY VARCHAR2(36)
AIRPORT VARCHAR2(58)
I inserted countries from airportdemodata to country table as under:
INSERT INTO country (country)
SELECT unique(country) from airportdemodata;
it worked fine.
Now I am trying to copy airportdemodata.city into city.city(country_id,city) by matching airportdemodata.country with country.country. I tried like this:
SQL> SELECT a.unique(city), b.country_id FROM airportdemodata a, country b where a.country=b.country;
SELECT a.unique(city), b.country_id FROM airportdemodata a, country b where a.country=b.country
*
ERROR at line 1:
ORA-01747: invalid user.table.column, table.column, or column specification

Right; inventing your own syntax usually leads to the outcome you experienced. Did you mean to use distinct?
SELECT DISTINCT a.city,
b.country_id
FROM airportdemodata a
JOIN country b ON a.country = b.country;

Related

SQL Query is taking too long even not responding

SQL> desc airport
Name Null? Type
----------------------------------------- -------- ----------------------------
AIRPORT_ID NOT NULL NUMBER(5)
CITY_ID NOT NULL NUMBER(5)
AIRPORT VARCHAR2(59)
IATA_CODE VARCHAR2(3)
SQL> desc city
Name Null? Type
----------------------------------------- -------- ----------------------------
CITY_ID NOT NULL NUMBER(5)
COUNTRY_ID NOT NULL NUMBER(5)
CITY VARCHAR2(36)
SQL> desc country
Name Null? Type
----------------------------------------- -------- ----------------------------
COUNTRY_ID NOT NULL NUMBER(5)
COUNTRY VARCHAR2(36)
Here is the query:
select airport_id, airport, iata_code, city, country
from airport a, city b, country c
where a.city_id = b.city_id
and b.country_id = c.country_id
and b.city like '%tehran%' or iata_code like '%tehran%'
order by airport asc;
This query is not responding or talking minutes to respond whilst when I ran same query with one parameter like and b.city like '%tehran%' by removing or iata_code like '%tehran%' then its running fine and results in less than a second
why its not responding with two parameters e.g. and b.city like '%tehran%' or iata_code like '%tehran%'
Looks like you want
select airport_id, airport, iata_code, city, country
from airport a
join city b on a.city_id=b.city_id and (b.city like '%tehran%' or b.iata_code like '%tehran%')
join country c on b.country_id=c.country_id
order by airport asc;
Note SQL standard JOIN syntax and the order of logical AND/OR operations fixed using brackets.

Oracle SQL : Data won't get inserted into super table

I am trying to create two classes, Persons and Customers. Customers being the subclass of Persons. When I try to insert values into Customers table, although I can see the value inserted in the customers table, I don't understand why it wouldn't get inserted into Persons table also as it is a superclass of customers. Is there a way I can insert into subclass through superclass or vice versa? Here is my code
CREATE TYPE PersonType AS OBJECT (
PID VARCHAR2(5),
Name VARCHAR2(30),
Address VARCHAR2(35),
age NUMBER(3)
) NOT FINAL;
/
CREATE TABLE Person of PersonType;
/
CREATE TYPE CustomerType UNDER PersonType (
CID VARCHAR2(20));
/
CREATE TABLE Customer of CustomerType;
/
INSERT INTO Customer VALUES(CustomerType('P2','Andy','Poland',21,'SS','C9'));
/
SELECT * FROM Person;
When you insert a row in an object table, it only goes in that table. Even if it's a subtype.
If you want the data in both person and customer, you need two inserts. But then you're duplicating the customer attributes!
When you have a type hierarchy, you can create an object table on the parent object. And insert subtypes into that. You only need to create a separate customer table if you want to only insert CustomerType objects into it.
If you insert all objects in the person table, you can pull out rows of a specific subtype with the is of (<objecttype>)' condition:
CREATE TYPE PersonType AS OBJECT (
PID VARCHAR2(5),
Name VARCHAR2(30),
Address VARCHAR2(35),
age NUMBER(3)
) NOT FINAL;
/
CREATE TYPE CustomerType UNDER PersonType (
CID VARCHAR2(20));
/
INSERT INTO Person VALUES(CustomerType('P2','Andy','Poland',21,'SS'));
INSERT INTO Person VALUES(PersonType('P3','Chris','Poland',21));
select * from person p;
PID NAME ADDRESS AGE
P2 Andy Poland 21
P3 Chris Poland 21
select * from person p
where value ( p ) is of ( CustomerType );
PID NAME ADDRESS AGE
P2 Andy Poland 21
But to be honest, you're better off storing the data using regular relational tables:
create table person (
pid varchar2(5)
primary key,
name varchar2(30),
address varchar2(35),
age number(3)
);
create table customer (
pid
references person ( pid )
not null,
cid varchar2(20)
);

Show the names of customers that have accounts SQL Query Oracle 10G

create table customer
(cust_id integer not null,
cust_name char(20) not null ,
cust_address varchar2(200) ,
emp_id integer not null,
constraint pk_customer primary key(cust_id)
);
create table account
(account_number integer not null,
account_balance number(8,2) not null,
constraint pk_acount primary key(account_number)
);
create table has
(cust_id integer not null,
account_number integer not null,
constraint pk_has
primary key(cust_id, account_number) )
alter table has
add constraint fk_account_has foreign key(account_number)
references account(account_number);
alter table has
add constraint fk_customer_has foreign key(cust_id)
references customer(cust_id);
Q1 Show the names of customers that have accounts
Q2 Show the customer names with the names of the employees they deal with**
Q1 is a simple lookup of the cust_id in junction table has:
select c.cust_name
from customer c
where exists (select 1 from has h where h.cust_id = c.cust_id)
This phrases as: select the customers that have at least one entry in the has table.
When it comes to Q2: your data structures show no sign of employees (all we have is customers and accounts), so this cannot be answered based on the information that you provided. You might want to ask a new question for this, providing sample data for the involved tables, along with desired results and you current attempt at solving the problem.

SQL DML Query AVG and COUNT

I am beginner at SQL and I am trying to create a query.
I have these tables:
CREATE TABLE Hospital (
hid INT PRIMARY KEY,
name VARCHAR(127) UNIQUE,
country VARCHAR(127),
area INT
);
CREATE TABLE Doctor (
ic INT PRIMARY KEY,
name VARCHAR(127),
date_of_birth INT,
);
CREATE TABLE Work (
hid INT,
ic INT,
since INT,
FOREIGN KEY (hid) REFERENCES Hospital (hid),
FOREIGN KEY (ic) REFERENCES Doctor (ic),
PRIMARY KEY (hid,ic)
);
The query is: What is the average in each country of the number of doctors working in hospitals of that country (1st column: each country, 2nd column: average)? Thanks.
You first need to write a query that counts the doctors per hospital
select w.hid, count(w.ic)
from work w
group by w.hid;
Based on that query, you can retrieve the average number of doctors per country:
with doctor_count as (
select w.hid, count(w.ic) as cnt
from work w
group by w.hid
)
select h.country, avg(dc.cnt)
from hospital h
join doctor_count dc on h.hid = dc.hid
group by h.country;
If you have an old DBMS that does not support common table expressions the above can be rewritten as:
select h.country, avg(dc.cnt)
from hospital h
join (
select w.hid, count(w.ic) as cnt
from work
group by w.hid
) dc on h.hid = dc.hid;
Here is an SQLFiddle demo: http://sqlfiddle.com/#!12/9ff79/1
Btw: storing date_of_birth as an integer is a bad choice. You should use a real DATE column.
And work is a reserved word in SQL. You shouldn't use that for a table name.

SQL Query (maybe simple)

So i'm having this problem.
I have two tables (Oracle), one is called Destination and the other one Reserve. Reserve has a foreign key to the id of Destination (Because on reserve has one destination). And reserve tuples means all the reserves that all the users have done. I need a way to check the top 3 most visited Destinations (based on the foreign key in the table Reserve).
How can I do that with SQL in Oracle. I know that I need to search within the Reserve tables for the 3 most repeated Destinations ID's, and later join that with the Destination table to get the details of the top 3 destinations.
Any help is valid. Thank you very much.
SCHEMA:
--------------------------------------------------------
-- File created - martes-septiembre-15-2009
--------------------------------------------------------
--------------------------------------------------------
-- DDL for Table DESTINO
--------------------------------------------------------
CREATE TABLE "S2501A29"."DESTINO"
( "PK_ID_DESTINO" NUMBER(10,0),
"FK_COD_UBICACION_GEOGRAFICA" NUMBER(10,0),
"NOMBRE" VARCHAR2(10),
"FOTO" VARCHAR2(30),
"DESCRIPCION" VARCHAR2(50)
) ;
--------------------------------------------------------
-- DDL for Table LUGAR_ESTADIA
--------------------------------------------------------
CREATE TABLE "S2501A29"."LUGAR_ESTADIA"
( "PK_ID_ESTADIA" NUMBER(10,0),
"NOMBRE" VARCHAR2(10),
"TIPO" VARCHAR2(10),
"DESCRIPCION" VARCHAR2(50),
"COSTO_SERVICIOS" NUMBER,
"DESCRIPCION_ALOJAMIENTO" VARCHAR2(100),
"DESCRIPCION_ALIMENTACION" VARCHAR2(100)
) ;
--------------------------------------------------------
-- DDL for Table OPCION_TRANSPORTE
--------------------------------------------------------
CREATE TABLE "S2501A29"."OPCION_TRANSPORTE"
( "PK_ID_VIAJE" NUMBER(10,0),
"MEDIO_TRANSPORTE" VARCHAR2(10),
"RESPONSABLE" VARCHAR2(10),
"CIUDAD_ORIGEN" VARCHAR2(10),
"CIUDAD_DESTINO" VARCHAR2(10),
"COSTO" NUMBER
) ;
--------------------------------------------------------
-- DDL for Table RESERVA
--------------------------------------------------------
CREATE TABLE "S2501A29"."RESERVA"
( "PK_ID_RESERVA" NUMBER(10,0),
"FK_COD_DESTINO" NUMBER(10,0),
"FK_COD_ESTADIA" NUMBER(10,0),
"FK_COD_VIAJE" NUMBER(10,0),
"TARJETA_CREDITO" VARCHAR2(12),
"FECHA_SALIDA" DATE,
"FECHA_REGRESO" DATE,
"NOMBRE_USUARIO" VARCHAR2(50)
) ;
--------------------------------------------------------
-- DDL for Table UBICACION_GEOGRAFICA
--------------------------------------------------------
CREATE TABLE "S2501A29"."UBICACION_GEOGRAFICA"
( "PK_ID_UBICACION" NUMBER(10,0),
"CIUDAD" VARCHAR2(10),
"PAIS" VARCHAR2(10),
"CONTINENTE" VARCHAR2(10)
) ;
Just a note:
RESERVE is Reserva
DESTINATION is Destino
Because the DB is in spanish. Thanks!
Maybe I'm missing something, but what about grouping by foreign key and sorting by the resulting values?
Edit: Something like:
select FK_COD_DESTINO, count(*) as qty from RESERVA group by FK_COD_DESTINO order by qty desc limit 3
Oracle doesn't support limit. This should work for you.
select A.FK_COD_DESTINO
, A.COUNT
, A.RANK
, B.*
from (select FK_COD_DESTINO
, count(*) as COUNT
, rank() over (order by count(*) desc) as RANK
from RESERVA
group by FK_COD_DESTINO) A
join DESTINO B on B.PK_ID_DESTINO = A.FK_COD_DESTINO
where A.RANK <= 3
you can try HAVING rownum <=3
How about:
WITH CountsByDestination
AS
(
SELECT FK_COD_DESTINO,
COUNT(*) CNT
FROM Reservations
GROUP BY DestinationId
),
RankingByDestination
AS
(
SELECT FK_COD_DESTINO,
CNT,
RANK() OVER (ORDER BY CNT) RNK
FROM CountsByDestination
)
SELECT *
FROM RankingByDestination R
INNER JOIN Destinations D ON D.PK_ID_DESTINO = R.FK_COD_DESTINO
WHERE R.RNK BETWEEN 1 AND 3
ORDER BY R.RNK
This retains ties, so if two or more destinations share the same counts they should appear as part of the result set.