How can I display if an airline departs from all the airport in my DB in Postgresql? - sql

I have 3 tables in my database:
CREATE TABLE airlines (
airline_name VARCHAR NOT NULL PRIMARY KEY
);
CREATE TABLE airport (
code VARCHAR UNIQUE NOT NULL PRIMARY KEY,
name VARCHAR NOT NULL,
category VARCHAR NOT NULL,
city VARCHAR NOT NULL
);
CREATE TABLE volo (
code VARCHAR UNIQUE NOT NULL PRIMARY KEY,
departure_time TIME(0) NOT NULL,
departure_airport VARCHAR NOT NULL REFERENCES aeroporto(codice),
arrival_time TIME(0) NOT NULL,
arrival_airport VARCHAR NOT NULL REFERENCES aeroporto(codice),
airline VARCHAR NOT NULL REFERENCES airlines(airline_name)
);
I need to display which airline departs from all the airport in my DB. Any suggestions?

You can use aggregation and count the departure_airport:
select v.airline
from volo v
group by v.airline
having count(distinct departure_airport) = (select count(*) from airport);

Related

How to make (patient id) forgein key in table of bill?

I try to create three tables by using website suport compiler any code but I have a problem in the table of the bill.
When I run it I get to error show me it is near in foreign key
These are codes of three tables
CREATE TABLE patient (
Patient Id (5) Primary key,
Name Varchar (20) Not null ,
Age Int Not null ,
Weight Int Not null ,
Gender Varchar (10) Not null,
Address Varchar (50) Not null ,
Disease Varchar (20) Not null
);
CREATE TABLE doctors (
DoctorId Varchar (5) Primary key,
Doctorname Varchar (15) Not null,
Dept Varchar (15) Not null
);
CREATE TABLE bill (
Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5) Foreign key,,
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null
);
Patient Table
CREATE TABLE patient
(
patient_id VARCHAR (5) PRIMARY KEY,
name VARCHAR (20) NOT NULL,
age INT NOT NULL,
weight INT NOT NULL,
gender VARCHAR (10) NOT NULL,
address VARCHAR (50) NOT NULL,
disease VARCHAR (20) NOT NULL
);
Errors
No data type has been assigned in Patient id column (Patient Id (5)
Primary key)
Patient id column name contains spaces. You need to
enclose the column name in double quotes or replace space with something else
(ex: _). It's not recommended to use spaces.
A column name with space
CREATE TABLE tablename ("column name" datatype);
Doctors Table
CREATE TABLE doctors
(
doctorid VARCHAR (5) PRIMARY KEY,
doctorname VARCHAR (15) NOT NULL,
dept VARCHAR (15) NOT NULL
);
Bill Table
CREATE TABLE bill
(
bill_no VARCHAR (50) PRIMARY KEY,
patient_id VARCHAR (5),
doctor_charge INT NOT NULL,
patient_type VARCHAR (10) NULL,
no_of_days INT NULL,
lab_charge INT NULL,
bill INT NOT NULL,
FOREIGN KEY (patient_id) REFERENCES patient(patient_id)
);
Errors
The way you have assigned foreign key is wrong. Please refer this and this article for more information. (Patient_Id Varchar (5) Foreign key,,)
There are two commans in the Patient_Id column (Patient_Id Varchar (5) Foreign key,,)
You have to provide reference of the table for which you want to use the reference key.
For example, you have table Persons which has Primary key PersonID, in that case if you want to use that as foreign key in another table, lets say Orders.
In Oracle
CREATE TABLE Orders (
OrderID numeric(10) not null,
OrderNumber numeric(10) not null,
PersonID numeric(10) not null,
CONSTRAINT fk_person_id
FOREIGN KEY (PersonID )
REFERENCES Persons(PersonID )
Your Case :
CREATE TABLE bill
( Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5),
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null,
CONSTRAINT fk_patient_id
FOREIGN KEY (Patient_Id)
REFERENCES patient(Patient_Id)
);
Remove the 'Foreign Key' from the table creation script.
Add this to your SQL script:
ALTER TABLE [Bill] WITH CHECK ADD CONSTRAINT [FK_Bill_Patient] FOREIGN KEY([Patient_Id])
REFERENCES [Patient] ([Patient_Id])
GO
ALTER TABLE [Bill] CHECK CONSTRAINT [FK_Bill_Patient]
GO
The words FOREIGN KEY are only needed for introducing the name of the FK constraint. Since your other constraints are not named, you might as well skip that part and go straight to REFERENCES.
If you specify a foreign key constraint as part of the column definition, you can omit the datatype to allow it to inherit from its parent at the time of creation, which I think is good practice as the types will automatically match.
We use VARCHAR2 in Oracle, not VARCHAR.
You don't need to specify NULL for columns that are allowed to be null.
I am not sure a 5-character string is a good datatype for a unique ID. How will you generate the values? Normally an auto-incrementing sequence number simplifies this.
create table doctors
( doctorid varchar2(5) primary key
, doctorname varchar2(15) not null
, dept varchar2(15) not null );
create table patients
( patient_id varchar2(5) primary key
, name varchar2(20) not null
, age integer not null
, weight integer not null
, gender varchar2(10) not null
, address varchar2(50) not null
, disease varchar2(20) not null );
create table bills
( bill_no varchar2(50) primary key
, patient_id references patients -- Allow datatype to inherit from parent
, patient_type varchar2(10)
, no_of_days integer
, lab_charge integer
, bill integer not null );

SQL Logic and Aggregate Issue

I have the following problem to solve in SQL :
d) A query that provides management information on take up of the various types of activities on offer. For each type of activity, the query should show the total number of individuals who took that type of activity and the average number of individuals taking each type of activity.
Here are my tables :
CREATE TABLE accommodations
(
chalet_number int PRIMARY KEY,
chalet_name varchar(40) NOT NULL,
no_it_sleeps number(2) NOT NULL,
indivppw number(4) NOT NULL
)
CREATE TABLE supervisors
(
supervisor_number int PRIMARY KEY,
supervisor_forename varchar(30) NOT NULL,
supervisor_surname varchar(30) NOT NULL,
mobile_number varchar(11) NOT NULL
)
CREATE TABLE visitors
(
visitor_ID int PRIMARY KEY,
group_ID int NOT NULL,
forename varchar(20) NOT NULL,
surname varchar(20) NOT NULL,
dob date NOT NULL,
gender varchar(1) NOT NULL
)
CREATE TABLE activities
(
activity_code varchar(10) PRIMARY KEY,
activity_title varchar(20) NOT NULL,
"type" varchar(20) NOT NULL
)
CREATE TABLE "groups"
(
group_ID int PRIMARY KEY,
group_leader varchar(20) NOT NULL,
group_name varchar(30)
number_in_group number(2) NOT NULL
)
CREATE TABLE bookings
(
group_ID int NOT NULL,
start_date date NOT NULL,
chalet_number int NOT NULL,
no_in_chalet number(2) NOT NULL,
start_date date NOT NULL,
end_date date NOT NULL,
CONSTRAINT bookings_pk PRIMARY KEY(group_ID, chalet_number));
CREATE TABLE schedule
(
schedule_ID int PRIMARY KEY,
activity_code varchar(10) NOT NULL,
time_of_activity number(4,2) NOT NULL,
am_pm varchar(2) NOT NULL,
"date" date NOT NULL
)
CREATE TABLE activity_bookings
(
visitor_ID int NOT NULL,
schedule_ID int NOT NULL,
supervisor_number int NOT NULL,
comments varchar(200),
CONSTRAINT event_booking_pk PRIMARY KEY(visitor_ID, schedule_ID));
ALTER TABLE visitors
ADD FOREIGN KEY (group_ID)
REFERENCES "groups"(group_ID)
ALTER TABLE Schedule
ADD FOREIGN KEY (activity_code)
REFERENCES activities(activity_code)
ALTER TABLE bookings
ADD FOREIGN KEY (group_ID)
REFERENCES "groups"(group_ID)
ALTER TABLE bookings
ADD FOREIGN KEY (chalet_number)
REFERENCES accommodations(chalet_number)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (visitor_ID)
REFERENCES visitors(visitor_ID)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (schedule_ID)
REFERENCES schedule(schedule_ID)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (supervisor_number)
REFERENCES supervisors(supervisor_number)
I have the following solution:
SELECT activities."type", 'overalltotal' AS OT, ('overalltotal' / 'activities') AS AVG
FROM activities, schedule
WHERE 'overalltotal' = (SELECT SUM(COUNT(schedule_ID))
FROM activities, schedule
WHERE schedule.activity_code = activities.activity_code
GROUP BY activities."type"
)
AND 'activities' = (SELECT COUNT(DISTINCT activities."type")
FROM activities
)
AND schedule.activity_code = activities.activity_code
GROUP BY activities."type";
I have implemented sample data and code to check the variables above:
SELECT SUM(COUNT(schedule_ID))
FROM activities, schedule
WHERE schedule.activity_code = activities.activity_code
GROUP BY activities."type";
Result : 20
SELECT COUNT(DISTINCT activities."type")
FROM activities;
Result : 5
However when running the code :
ORA-01722: invalid number
01722. 00000 - "invalid number"
*Cause:
*Action:
EDIT:
Using Dave's Code i have the following output:
Snowboarding 15
sledding 19
Snowmobiling 6
Ice Skating 5
Skiing 24
How would i do the final part of the question?
and the average number of individuals taking each type of activity.
You must use double quotes around column names in Oracle, not single quotes. For example, "overalltotal". Single quotes are for text strings, which is why you're getting an invalid number error.
EDIT: This is probably the type of query you want to use:
SELECT activities."type", COUNT(*) AS total, COUNT(*)/(COUNT(*) OVER ()) AS "avg"
FROM activities a
JOIN schedule s ON a.activity_code=s.activity_code
JOIN activity_bookings ab ON s.schedule_ID=ab.schedule_ID
GROUP BY activities."type";
Basically, because each activity booking has one visitor id, we want to get all the activity bookings for each activity. We have to go through schedule to do that. They we group the rows by the activity type and count how many activity bookings we have for each type.

st_distance using parents geometry

I have two parent tables as below
CREATE TABLE GISD.CUSTOMERS
(CUSTOMER_ID INTEGER NOT NULL,
FIRST_NAME VARCHAR (15) NOT NULL,
SURNAME VARCHAR (20) NOT NULL,
DATE_OF_BIRTH DATE NOT NULL,
HOUSE_NUMBER VARCHAR (5) NOT NULL
POST_CODE VARCHAR(8) NOT NULL,
STREET VARCHAR (25) NOT NULL,
TOWN VARCHAR (25) NOT NULL
);
SELECT ADDGEOMETRYCOLUMN('gisd','customers', 'customers_geom', '27700','POINT',2);
and
CREATE TABLE GISD.CINEMAS
(CINEMA_ID INTEGER NOT NULL,
CINEMA_NAME VARCHAR(25) NOT NULL,
ADDRESS_NUMBER INTEGER NOT NULL,
POST_CODE VARCHAR(8) NOT NULL,
STREET VARCHAR (25) NOT NULL,
TOWN VARCHAR (25) NOT NULL,
OPENING_TIME TIME NOT NULL,
CLOSING_TIME TIME NOT NULL
);
SELECT ADDGEOMETRYCOLUMN('gisd','cinemas', 'cinemas_geom', '27700','POLYGON',2);
SELECT ADDGEOMETRYCOLUMN('gisd','cinemas', 'centroid', '27700','POINT',2);
I have a child which uses foreign keys from both these tables as such:
CREATE TABLE GISD.BOOKING
(BOOKING_ID INTEGER NOT NULL,
CUSTOMER_ID INTEGER NOT NULL,
CINEMA_ID INTEGER NOT NULL,
TIME TIME NOT NULL,
DATE DATE NOT NULL,
FILM VARCHAR(50) NOT NULL,
BOOKING_METHOD VARCHAR (15) NOT NULL,
BOOKING_FEE NUMERIC NOT NULL -- Numeric is suggested by postgresql.org for currency
TICKET_PRICE NUMERIC NOT NULL
);
is there a way that will allow me to take a unique booking id and reference back to the customer geometry and cinema geometry to calculate an ST_Distance? I assume some sort of nested query could do this but am having no luck?
cheers
UPDATE (from comment)
I have tried the following code:
SELECT (ST_DISTANCE(
(SELECT centroid
FROM GISD.CINEMAS
INNER JOIN GISD.BOOKING ON CINEMAS.CINEMA_ID=BOOKING.CINEMA_ID
),(
SELECT customers_geom
FROM GISD.CUSTOMERS
INNER JOIN GISD.BOOKING ON CUSTOMERS.CUSTOMER_ID=BOOKING.CUSTOMER_ID
)
))
but get an error saying 'more than one row returned by a subquery used as an expression' Any ideas how to get round this? I ideally want it to return the distance for each booking ID
Corrected schema with primary/foreign keys and LOWERCASED names.
DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp;
SET search_path=tmp;
CREATE TABLE tmp.customers
( customer_id INTEGER NOT NULL PRIMARY KEY
, first_name VARCHAR (15) NOT NULL
, surname VARCHAR (20) NOT NULL
, date_of_birth DATE NOT NULL
, house_number VARCHAR (5) NOT NULL
, post_code VARCHAR(8) NOT NULL
, street VARCHAR (25) NOT NULL
, town VARCHAR (25) NOT NULL
);
SELECT addgeometrycolumn('tmp','customers', 'customers_geom', '27700','POINT',2);
-- and
CREATE TABLE tmp.cinemas
( cinema_id INTEGER NOT NULL PRIMARY KEY
, cinema_name VARCHAR(25) NOT NULL
, address_number INTEGER NOT NULL
, post_code VARCHAR(8) NOT NULL
, street VARCHAR (25) NOT NULL
, town VARCHAR (25) NOT NULL
, opening_time TIME NOT NULL
, closing_time TIME NOT NULL
);
SELECT addgeometrycolumn('tmp','cinemas', 'cinemas_geom', '27700','POLYGON',2);
SELECT addgeometrycolumn('tmp','cinemas', 'centroid', '27700','POINT',2);
-- I have a junction table between these tables as such:
CREATE TABLE tmp.BOOKING
( booking_id INTEGER NOT NULL PRIMARY KEY
, customer_id INTEGER NOT NULL REFERENCES tmp.customers (customet_id)
, cinema_id INTEGER NOT NULL REFERENCES tmp.cinemas (cinema_id)
, zdatetime timestamp NOT NULL
, film VARCHAR(50) NOT NULL
, booking_method VARCHAR (15) NOT NULL
, booking_fee NUMERIC NOT NULL
, ticket_price NUMERIC NOT NULL
);
Skeleton for 3-way join:
SELECT bo.booking_id, bo.zdatetime, bo.film
, ci.cinemas_geom
, ci.centroid
, cu.customers_geom
FROM booking bo
JOIN customers cu ON cu.customer_id = bo.customer_id
JOIN cinemas ci ON ci.cinema_id = bo.cinema_id
;
Now, just add the function call, using the results from the skeletton as function arguments (I am not that fluent in GIS, this is only an example to demonstrate the syntax):
SELECT bo.booking_id, bo.zdatetime, bo.film
, st_distance(ci.centroid , cu.customers_geom ) AS the_distance
FROM booking bo
JOIN customers cu ON cu.customer_id = bo.customer_id
JOIN cinemas ci ON ci.cinema_id = bo.cinema_id
;

SQL 2008 create table method and KEY

I've got a script that generates a table - only my version of SQL 2008 throws up an error - has the syntax changed? Or how do I fix it manually?
CREATE TABLE ScoHistory (
CourseID varchar (255) NOT NULL ,
SessionID int NOT NULL ,
ScoID varchar (255) NOT NULL ,
StudentID varchar (255) NOT NULL ,
DateRecorded datetime NULL ,
score_raw varchar (12) NULL,
KEY student_course_sess_scohist_idx (StudentID, CourseID, SessionID, ScoID) -- this is the bit it doesn't like! It says incorrect syntax near KEY...
);
Many thanks in advance,
Spud
You can define a named primary key table constraint like this:
CREATE TABLE ScoHistory (
CourseID varchar (255) NOT NULL,
SessionID int NOT NULL,
ScoID varchar (255) NOT NULL,
StudentID varchar (255) NOT NULL,
DateRecorded datetime NULL,
score_raw varchar (12) NULL,
CONSTRAINT student_course_sess_scohist_idx PRIMARY KEY (StudentID, CourseID, SessionID, ScoID)
);
It would work like this, if this is the intended behaviour:
CREATE TABLE ScoHistory (
CourseID varchar (255) NOT NULL ,
SessionID int NOT NULL ,
ScoID varchar (255) NOT NULL ,
StudentID varchar (255) NOT NULL ,
DateRecorded datetime NULL ,
score_raw varchar (12) NULL,
PRIMARY KEY (StudentID, CourseID, SessionID, ScoID)
);
It you would only like to create a non-unique index on the table, create the index using the CREATE INDEX statement.
CREATE TABLE ScoHistory
(
CourseID varchar(255) NOT NULL
,SessionID int NOT NULL
,ScoID varchar(255) NOT NULL
,StudentID varchar(255) NOT NULL
,DateRecorded datetime NULL
,score_raw varchar(12) NULL,
) ;
ALTER TABLE dbo.ScoHistory ADD
CONSTRAINT PK_ScoHistory PRIMARY KEY (StudentID, CourseID, SessionID, ScoID);

Where clause in Mutiple table sql joins

TABLES
CREATE TABLE LocalBusiness
(
BusinessID INT NOT NULL PRIMARY KEY,
BusinessName VARCHAR2 (20) NOT NULL,
TypeID INT,
Latitude DECIMAL (10,2),
Longitude DECIMAL (10,2),
Web_address VARCHAR2 (50) NOT NULL,
Postcode VARCHAR2 (10) NOT NULL,
official_rating int,
min_price NUMBER(4,2),
max_price NUMBER(4,2),
FOREIGN KEY (TypeID) REFERENCES LocalBusinessType (TypeID),
CONSTRAINT chk_Officialrating CHECK (official_rating> 0 AND official_rating<6 )
);
CREATE TABLE Address
(
AddressID INT NOT NULL PRIMARY KEY,
BusinessID INT,
AreaID INT,
Address VARCHAR2 (50) NOT NULL,
Postcode VARCHAR2 (10) NOT NULL,
FOREIGN KEY (BusinessID) REFERENCES LocalBusiness (BusinessID),
FOREIGN KEY (AreaID) REFERENCES Area (AreaID)
);
CREATE TABLE Phone
(
PhoneNoID INT NOT NULL PRIMARY KEY,
PhoneNo VARCHAR2 (15) NOT NULL,
BusinessID INT,
Description VARCHAR2 (50) NOT NULL,
FOREIGN KEY (BusinessID) REFERENCES LocalBusiness (BusinessID),
CONSTRAINT PhoneNo_unique UNIQUE (PhoneNo)
);
CREATE TABLE Email
(
EmailID INT NOT NULL PRIMARY KEY,
email_address VARCHAR2 (50) NOT NULL,
BusinessID INT,
Description VARCHAR2 (50) NOT NULL,
FOREIGN KEY (BusinessID) REFERENCES LocalBusiness (BusinessID),
CONSTRAINT email_unique UNIQUE (email_address)
);
CREATE TABLE Area
(
AreaID INT NOT NULL PRIMARY KEY,
AreaName VARCHAR2 (20) NOT NULL,
Region VARCHAR2 (20) NOT NULL
);
SELECT statement:
SELECT
LocalBussiness.BusinessName, Address.Address, Address.Postcode,
Area.AreaName, Area.Region, LocalBusiness.OfficialRating,
LocalBusiness.min_price, LocalBusiness_max_price,
Phone.description, Phone.PhoneNo,
Email.Description, Email.email_address,
LocalBusiness.Web_address
FROM
LocalBusiness
JOIN
Address ON LocalBusiness.BusinessID = Address.BusinessID
JOIN
Area ON Address.AreaID = Area.AreaID
AND LocalBusiness.BusinessID = Address.BusinessID
JOIN
Phone ON Phone.BusinessID = LocalBusiness.BusinessID
JOIN
Email ON Email.BusinessID = LocalBusiness.BusinessID
WHERE
TypeID = '1'
ORDER BY
LocalBusiness.BusinessName ASC;
The where clause in the sql join statement written above seem to be ineffective as the some values for the TypeID return incomplete data while others return no rows at all. How do I go about fixing this?
Yyou repeat a condition
AND LocalBusiness.BusinessID=Address.BusinessID in JOIN Area
Try avoinding this repetition
SELECT LocalBussiness.BusinessName, Address.Address, Address.Postcode,
Area.AreaName, Area.Region, LocalBusiness.OfficialRating,
LocalBusiness.min_price, LocalBusiness_max_price, Phone.description,
Phone.PhoneNo, Email.Description, Email.email_address,
LocalBusiness.Web_address
FROM LocalBusiness
JOIN Address ON LocalBusiness.BusinessID=Address.BusinessID
JOIN Area ON Address.AreaID=Area.AreaID
JOIN Phone ON Phone.BusinessID=LocalBusiness.BusinessID
JOIN Email ON Email.BusinessID=LocalBusiness.BusinessID
WHERE TypeID = '1'
ORDER BY LocalBusiness.BusinessName ASC;
Otherwise check th consistence of your data ..