I have four tables, one of them named matches and another one named teams. I need to display the teamCode in teams with the number of point they have that we can calculate in matches. Each win is 2 points each draw one point and each lost zero.
CREATE TABLE divisions
(
codediv CHAR(1) NOT NULL,
nomdiv VARCHAR2(40)
);
ALTER TABLE divisions
ADD CONSTRAINT divisions_pk PRIMARY KEY (codediv);
CREATE TABLE teams
(
teamCode CHAR(3) NOT NULL,
teamName VARCHAR2(50),
codediv CHAR(1) NOT NULL,
ville VARCHAR2(40),
nbcoupes NUMBER
);
ALTER TABLE teams ADD CHECK (nbcoupes >= 0);
ALTER TABLE teams ADD CONSTRAINT teams_pk PRIMARY KEY (teamCode);
CREATE TABLE joueurs
(
numjoueur NUMBER(3) NOT NULL,
nom VARCHAR2(30),
prenom VARCHAR2(30),
codeequipe CHAR(3)
);
ALTER TABLE joueurs ADD CONSTRAINT joueurs_pk PRIMARY KEY (numjoueur);
CREATE TABLE matchs
(
MatchNumber NUMBER(4) NOT NULL,
datematch DATE,
codeVisitingTeam CHAR(3) NOT NULL,
codeReceivingTeam CHAR(3) NOT NULL,
scoreVisitingTeam NUMBER(2),
scoreReceivingTeam NUMBER(2)
);
ALTER TABLE matchs ADD CONSTRAINT matchs_pk PRIMARY KEY (MatchNumber);
CREATE TABLE statistiques
(
nummatch NUMBER(4) NOT NULL,
numjoueur NUMBER(3) NOT NULL,
nbbuts NUMBER(3),
nbpasse NUMBER(3)
);
ALTER TABLE statistiques
ADD CONSTRAINT statistiques_pk PRIMARY KEY (numjoueur, nummatch);
ALTER TABLE matchs
ADD CONSTRAINT codeVisitingTeam FOREIGN KEY ( codeVisitingTeam)
REFERENCES teams ( teamCode );
ALTER TABLE teams
ADD CONSTRAINT teams_divisions_fk FOREIGN KEY ( codediv )
REFERENCES divisions ( codediv );
ALTER TABLE joueurs
ADD CONSTRAINT joueurs_equipes_fk FOREIGN KEY ( teamCode )
REFERENCES equipes ( teamCode );
ALTER TABLE matchs
ADD CONSTRAINT matchs_equipes_fk FOREIGN KEY ( CodeReceivingTeam )
REFERENCES equipes ( teamCode );
ALTER TABLE statistiques
ADD CONSTRAINT statistiques_joueurs_fk FOREIGN KEY ( numjoueur )
REFERENCES joueurs ( numjoueur );
ALTER TABLE statistiques
ADD CONSTRAINT statistiques_matchs_fk FOREIGN KEY ( nummatch )
REFERENCES matchs ( nummatch );
insert into divisions values('O', 'OUEST');
insert into divisions values('E', 'EST');
insert into equipes values('MTL', 'LES CANADIENS DE MONTRÉAl', 'E', 'MONTRÉAl', 24);
insert into equipes values('TOR', 'LES MAPLE LEAFS', 'E', 'TORONTO', 22);
insert into equipes values('OTT', 'LES SÉNATEURS', 'E', 'OTTAWA', 4);
insert into equipes values('AVL', 'LES AVALANCHES', 'O', 'COLORADO', 2);
insert into equipes values('VAN', 'LES CANUKS', 'O', 'VANCOUVER', 1);
insert into equipes values('BRU', 'LES BRUNS DE BOSTON', 'E', 'BOSTON', 13);
insert into Joueurs values(1, 'PRICE', 'CAREY', 'MTL');
insert into Joueurs values(2, 'MARKOV', 'ANDRÉ', 'MTL');
insert into Joueurs values(3, 'SUBBAN', 'KARL', 'MTL');
insert into Joueurs values(4, 'PATIORETTY', 'MAX', 'MTL');
insert into Joueurs values(10, 'HAMMOND', 'ANDREW', 'OTT');
insert into Joueurs values(6, 'STONE', 'MARC', 'OTT');
insert into Joueurs values(9, 'TURIS', 'KYLE', 'OTT');
insert into Joueurs values(7, 'GALLAGHER', 'BRANDON', 'MTL');
insert into Joueurs values(8, 'TANGUAY', 'ALEX', 'AVL');
insert into Joueurs values(11, 'THOMAS', 'BIL', 'AVL');
insert into Joueurs values(5, 'PATOCHE', 'ALAIN', NULL);
insert into Joueurs values(12, 'POIRIER', 'JUTEUX', NULL);
insert into Matchs values(100, TO_DATE('18-10-30', 'YY/MM/DD'), 'MTL', 'TOR', 3 , 4);
insert into Matchs values(101, TO_DATE('18-11-10', 'YY/MM/DD'), 'TOR', 'MTL', 3 , 3);
insert into Matchs values(102, TO_DATE('18-10-12', 'YY/MM/DD'), 'MTL', 'OTT', 2 , 0);
insert into Matchs values(103, TO_DATE('18-10-20', 'YY/MM/DD'), 'OTT', 'MTL', 0 , 1);
insert into Matchs values(104, TO_DATE('18-11-30', 'YY/MM/DD'), 'MTL', 'AVL', 3 , 4);
insert into Matchs values(105, TO_DATE('18-11-10', 'YY/MM/DD'), 'AVL', 'MTL', 0 , 0);
insert into Matchs values(106, TO_DATE('18-12-12', 'YY/MM/DD'), 'MTL', 'VAN', 2 , 0);
insert into Matchs values(107, TO_DATE('18-03-17', 'YY/MM/DD'), 'VAN', 'MTL', 3 , 1);
insert into Matchs values(108, TO_DATE('18-11-30', 'YY/MM/DD'), 'OTT', 'VAN', 0 , 0);
insert into Matchs values(109, TO_DATE('18-11-10', 'YY/MM/DD'), 'OTT', 'TOR', 0 , 4);
insert into Matchs values(114, TO_DATE('18-10-30', 'YY/MM/DD'), 'BRU', 'TOR', 3 , 4);
insert into Matchs values(115, TO_DATE('19-02-15', 'YY/MM/DD'), 'AVL', 'TOR', null , null);
insert into Matchs values(120, TO_DATE('18-02-26', 'YY/MM/DD'), 'MTL', 'AVL', null , null);
insert into Matchs values(121, TO_DATE('19-02-20', 'YY/MM/DD'), 'MTL', 'OTT', null , null);
Insert into statistiques values(100,3,2,2);
Insert into statistiques values(100,7,1,1);
Insert into statistiques values(101,3,1,0);
Insert into statistiques values(101,7,0,1);
Insert into statistiques values(101,4,1,2);
Insert into statistiques values(101,2,1,2);
Insert into statistiques values(100,4,0,2);
Insert into statistiques values(102,3,1,1);
Insert into statistiques values(102,7,1,2);
Insert into statistiques values(102,9,0,1);
Insert into statistiques values(106,4,1,1);
Insert into statistiques values(106,3,0,2);
Insert into statistiques values(106,2,1,0);
Insert into statistiques values(100,1,null,null);
Insert into statistiques values(101,1,null,null);
Insert into statistiques values(103,1,null,null);
Insert into statistiques values(102,1,null,null);
I've started with this to get the winning teams
select *
from
(select v.teamcode, count(m.codeVisitingTeam) as WonMatches
from matchs m
join teams v on v.teamCode = m.codeVisitingTeam
where m.scoreVisitingTeam > m.scoreReceivingTeam
group by v.teamCode
union all
select r.codeequipe, count(m.codeequiper) as WonMatches
from matchs m
join teams r on r.teamCode = m.codeReceivingTeam
where m.scoreReceivingTeam > m.scoreVisitingTeam
group by r.teamCode));
The only problem with the code above is that it returns twice the team 'MTL' as so :
VAN 1
MTL 2
AVL 1
TOR 3
MTL 1
So I was having a bit of fun with your query and did a bit more than you asked. I wrote the following query to calculated the full complement of wins, losses, and ties. I then ordered the results by points (3 points for a win and 1 for a draw). I hope this helps you a bit:
SELECT *
FROM (SELECT TeamCode,
CASE
WHEN (team = 'VISTING' AND scoreVisitingTeam > SCORERECEIVINGTEAM) OR (team = 'RECEIVING' AND SCORERECEIVINGTEAM > SCOREVISITINGTEAM) THEN 'WIN'
WHEN (team = 'VISTING' AND scoreVisitingTeam < SCORERECEIVINGTEAM) OR (team = 'RECEIVING' AND SCORERECEIVINGTEAM < SCOREVISITINGTEAM) THEN 'LOSS'
ELSE 'DRAW'
END AS RESULT
FROM matchs
UNPIVOT (TeamCode FOR Team IN (CodeVisitingTeam AS 'VISTING', CodeReceivingTeam AS 'RECEIVING')))
PIVOT(COUNT(*) FOR RESULT IN ('WIN' AS WINS, 'LOSS' AS LOSSES, 'DRAW' AS DRAWS))
ORDER BY (wins*3)+draws DESC;
If you have questions, please let me know.
I also created a SQLFiddle. (Link) Note: I removed your constraints from the SQLFiddle. They were throwing errors and I didn't feel like debugging it.
You can do it in a single query with conditional aggregation:
select e.teamCode,
sum(
case
when (e.teamCode = m.codeReceivingTeam and m.scoreReceivingTeam > m.scoreVisitingTeam)
or (e.teamCode = m.codeVisitingTeam and m.scoreReceivingTeam < m.scoreVisitingTeam) then 2
when m.scoreReceivingTeam = m.scoreVisitingTeam then 1
else 0
end
) total_points
from equipes e inner join matchs m
on e.teamCode in (m.codeReceivingTeam, m.codeVisitingTeam)
group by e.teamCode
Related
I have build my database ofcourse etc but I have problem with the code.I try to solve that
"Names of marines(one time each one) that have for reservation red boat and their have tonnage bigger than 200." and I did that.
Select distinct m.name
From marina m join reservation r on (m.mid, r.mid)
Where r.bid = (select b.bid from boat b where b.color = "red")
I tryed use that https://senseful.github.io/text-table/ but I failed so I post here if someone can help edited.That is my database.
drop table if exists reservation;
drop table if exists marina;
drop table if exists boat;
drop table if exists sailor;
create table boat
(bid integer not null constraint c_bid primary key,
bname varchar(40),
color varchar(40)
constraint c_color check (color in ('Red','Blue','Light Green','Yellow')));
create table marina
(mid integer not null constraint m_key primary key,
name varchar(40) not null,
capacity integer);
create table sailor
(sid integer not null constraint c_sid primary key,
sname varchar(40),
rating integer
constraint c_rating check (rating between 1 and 10),
age real constraint
c_age check (age < 18 OR age = 18));
create table reservation
(sid integer not null constraint f_key1 references sailor(sid) on delete cascade,
bid integer not null constraint f_key2 references boat(bid) on delete restrict
constraint c_bid check (bid not in (999)),
mid integer constraint f_key3 references marina(mid) on delete set null,
r_date date not null constraint c_date check (r_date > '02/04/1998'),
constraint p_key primary key(sid,bid,r_date));
INSERT INTO sailor(sid,sname,rating,age) VALUES (2, 'John', 6, 17);
INSERT INTO sailor(sid,sname,rating,age) VALUES (11, 'Mary', 10, 18);
INSERT INTO sailor(sid,sname,rating,age) VALUES (12, 'TH', 7, 14);
INSERT INTO sailor(sid,sname,rating,age) VALUES (13, 'John', 9, 18);
INSERT INTO sailor(sid,sname,rating,age) VALUES (1, 'Christin', 10, 17);
INSERT INTO sailor(sid,sname,rating,age) VALUES (15, 'Thod', 10, 13);
INSERT INTO sailor(sid,sname,rating,age) VALUES (16, 'Leonid', 5, 13);
INSERT INTO sailor(sid,sname,age) VALUES (17,'Left',17);
INSERT INTO sailor(sid,sname,rating,age) VALUES (19,'Polu',1,16);
INSERT INTO sailor(sid,sname,rating,age) VALUES (27,'Marinin',8,15);
INSERT INTO sailor(sid,sname,rating,age) VALUES (37,'Cos',8,14);
INSERT INTO marina(mid,name,capacity) VALUES(33,'Porto',300);
INSERT INTO marina(mid,name,capacity) VALUES(5,'Calam',105);
INSERT INTO marina(mid,name,capacity) VALUES(1,'Plat',32);
INSERT INTO marina(mid,name,capacity) VALUES(7,'Pos',19);
INSERT INTO marina(mid,name,capacity) VALUES(2,'Our',105);
INSERT INTO boat(bid,bname,color) VALUES(88,'Sof','Blue');
INSERT INTO boat(bid,bname,color) VALUES(17,'Ag','Light Green');
INSERT INTO boat(bid,bname,color) VALUES(13,'Panag','Yellow');
INSERT INTO boat(bid,bname,color) VALUES(1,'Αg.N','Red');
INSERT INTO boat(bid,bname,color) VALUES(72,'Christin','Red');
INSERT INTO boat(bid,bname,color) VALUES(19,'Dil','Light Green');
INSERT INTO boat(bid,bname,color) VALUES(77,'Αg.G','Blue');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(2,88,7,'1999-02-17');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(12,17,2,'1998-05-17');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(11,17,2,'1999-01-17');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(13,13,7,'2003-01-13');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(11,13,33,'2000-05-05');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(1,1,33,'2000-05-05');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(1,13,33,'2000-05-06');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(1,17,33,'2000-05-07');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(1,19,33,'2000-05-08');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(1,72,33,'2000-05-09');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(1,88,33,'2000-05-10');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(1,77,2,'2000-08-10');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(19,13,33,'1999-10-12');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(27,88,7,'2000-06-11');
INSERT INTO reservation(sid,bid,mid,r_date) VALUES(37,72,2,'2001-04-27');
This can be solved with an EXISTS sub-query:
select m.*
from marina m
where m.capacity > 200
and exists (select *
from reservation r
join boat b on r.bid = b.bid
where mid = m.mid
and b.color = 'Red')
where m.capacity > 200 only selects marinas with a capacity that is bigger than 200 (this is how I understand the "have tonnage bigger than 200")
The (co-related) sub-query then checks for reservations for each marina that were made for a red boat (that's how I understand the "that have for reservation red boat" part).
Online example
So I'm working on a SQL and I keep getting errors and I have triple checked it and still haven't come up with a reason as to why the queries aren't showing up correctly. I'm using Microsoft SQL Server. These are the errors that I'm currently getting:
Msg 1767, Level 16, State 0, Line 2
Foreign key 'FK_PatientID' references invalid table 'Patient'.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint. See previous errors.
Msg 208, Level 16, State 1, Line 2
Invalid object name 'TreatmentDetails'.
Code:
IF EXISTS (SELECT name FROM sys.databases WHERE name = N'Hospital')
DROP DATABASE [Hospital]
GO
CREATE DATABASE [Hospital]
GO
USE Hospital
GO
CREATE TABLE [dbo].[Physician]
(
PhysicianID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
Specialty VARCHAR(30) NOT NULL,
GraduationDate DATE NOT NULL,
CONSTRAINT [PK_PhysicianID] PRIMARY KEY (PhysicianID)
);
GO
CREATE TABLE [dbo].[TreatmentDetails]
(
TreatmentID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
StartDateTime DATE NOT NULL,
EndDateTime DATE NULL,
Results VARCHAR(30),
CONSTRAINT [PK_TreatmentID] PRIMARY KEY (TreatmentID),
CONSTRAINT [FK_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
CREATE TABLE [dbo].[Patient]
(
PatientID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
DateOfBirth DATE NOT NULL,
CONSTRAINT [PK_PatientID] PRIMARY KEY (PatientID),
);
GO
CREATE TABLE [dbo].[AdmissionDate]
(
AdmissionID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
AdmissionDate DATE NOT NULL,
DischargeDate DATE NULL,
CONSTRAINT [PK_AdmissionID] PRIMARY KEY (AdmissionID),
CONSTRAINT [FK_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
INSERT INTO TreatmentDetails VALUES (1, 12345, 1234, '2014-4-5', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (2, 12346, 1235, '2013-5-6', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (3, 12347, 1236, '2012-7-8', '2014-9-10', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (4, 12348, 1237, '2011-9-10', '2013-11-12', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (5, 12349, 1238, '2010-11-12', NULL, 'NOT DONE')
INSERT INTO Physician VALUES (12345, 'Will', 'Smith', 'Surgeon', '2014-5-9');
INSERT INTO Physician VALUES (12346, 'Jim', 'Carey', 'Pediatrictian', '2013-2-4');
INSERT INTO Physician VALUES (12347, 'Adam', 'Sandler', 'Immunologist', '2012-6-12');
INSERT INTO Physician VALUES (12348, 'Seth', 'Rogan', 'Neurologist', '2010-9-19');
INSERT INTO Physician VALUES (12349, 'James', 'Bond', 'Dermatologist', '2011-5-2');
INSERT INTO Patient VALUES (1234, 'Christopher', 'Thompson', '1989-7-9');
INSERT INTO Patient VALUES (1235, 'Mac', 'Miller', '1970-9-5');
INSERT INTO Patient VALUES (1236, 'Abraham', 'Lincoln', '1988-1-22');
INSERT INTO Patient VALUES (1237, 'George', 'Washington', '1965-2-8');
INSERT INTO Patient VALUES (1238, 'Franklin', 'Roosevelt', '1992-5-19');
INSERT INTO AdmissionDate VALUES (001, 12345, 1234,'2014-2-9', NULL);
INSERT INTO AdmissionDate VALUES (002, 12346, 1235, '2014-12-8', '2014-15-9');
INSERT INTO AdmissionDate VALUES (003, 12347, 1236,'2014-3-7', '2014-4-9');
INSERT INTO AdmissionDate VALUES (004, 12348, 1237, '2014-8-6', NULL);
INSERT INTO AdmissionDate VALUES (005, 12349, 1238, '2014-5-5', NULL);
GO
USE Hospital
SELECT * FROM Physician
SELECT * FROM Patient
SELECT * FROM AdmissionDate
SELECT * FROM TreatmentDetails
SELECT Patient.PatientID, Patient.FirstName, Patient.LastName, Patient.DateOfBirth, AdmissionDate.AdmissionDate, AdmissionDate.DischargeDate, Physician.Specialty
FROM Patient, AdmissionDate, Physician
WHERE AdmissionDate IS NOT NULL
ORDER BY Patient.LastName, Patient.FirstName, AdmissionDate.AdmissionDate
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NOT NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName
You have incorrect order of creating tables.
You are creating foreign keys with same name in different tables.
You are inserting data in tables in incorrect order.
You have provided incorrect date format. Default format is YYYY-MM-DD
and you provide INSERT INTO AdmissionDate VALUES (002, 12346, 1235, '2014-12-8', '2014-15-9'); 2014-15-9 this is to change.
Here is working script:
USE master
IF EXISTS (SELECT name FROM sys.databases WHERE name = N'Hospital')
DROP DATABASE [Hospital]
GO
CREATE DATABASE [Hospital]
GO
USE Hospital
GO
CREATE TABLE [dbo].[Physician]
(
PhysicianID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
Specialty VARCHAR(30) NOT NULL,
GraduationDate DATE NOT NULL,
CONSTRAINT [PK_PhysicianID] PRIMARY KEY (PhysicianID)
);
GO
CREATE TABLE [dbo].[Patient]
(
PatientID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
DateOfBirth DATE NOT NULL,
CONSTRAINT [PK_PatientID] PRIMARY KEY (PatientID),
);
GO
CREATE TABLE [dbo].[TreatmentDetails]
(
TreatmentID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
StartDateTime DATE NOT NULL,
EndDateTime DATE NULL,
Results VARCHAR(30),
CONSTRAINT [PK_TreatmentDetails_TreatmentID] PRIMARY KEY (TreatmentID),
CONSTRAINT [FK_TreatmentDetails_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_TreatmentDetails_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
CREATE TABLE [dbo].[AdmissionDate]
(
AdmissionID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
AdmissionDate DATE NOT NULL,
DischargeDate DATE NULL,
CONSTRAINT [PK_AdmissionDate_AdmissionID] PRIMARY KEY (AdmissionID),
CONSTRAINT [FK_AdmissionDate_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_AdmissionDate_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
INSERT INTO Physician VALUES (12345, 'Will', 'Smith', 'Surgeon', '2014-5-9');
INSERT INTO Physician VALUES (12346, 'Jim', 'Carey', 'Pediatrictian', '2013-2-4');
INSERT INTO Physician VALUES (12347, 'Adam', 'Sandler', 'Immunologist', '2012-6-12');
INSERT INTO Physician VALUES (12348, 'Seth', 'Rogan', 'Neurologist', '2010-9-19');
INSERT INTO Physician VALUES (12349, 'James', 'Bond', 'Dermatologist', '2011-5-2');
INSERT INTO Patient VALUES (1234, 'Christopher', 'Thompson', '1989-7-9');
INSERT INTO Patient VALUES (1235, 'Mac', 'Miller', '1970-9-5');
INSERT INTO Patient VALUES (1236, 'Abraham', 'Lincoln', '1988-1-22');
INSERT INTO Patient VALUES (1237, 'George', 'Washington', '1965-2-8');
INSERT INTO Patient VALUES (1238, 'Franklin', 'Roosevelt', '1992-5-19');
INSERT INTO TreatmentDetails VALUES (1, 12345, 1234, '2014-4-5', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (2, 12346, 1235, '2013-5-6', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (3, 12347, 1236, '2012-7-8', '2014-9-10', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (4, 12348, 1237, '2011-9-10', '2013-11-12', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (5, 12349, 1238, '2010-11-12', NULL, 'NOT DONE')
INSERT INTO AdmissionDate VALUES (001, 12345, 1234,'2014-2-9', NULL);
INSERT INTO AdmissionDate VALUES (002, 12346, 1235, '2014-12-8', '2014-9-15');
INSERT INTO AdmissionDate VALUES (003, 12347, 1236,'2014-3-7', '2014-4-9');
INSERT INTO AdmissionDate VALUES (004, 12348, 1237, '2014-8-6', NULL);
INSERT INTO AdmissionDate VALUES (005, 12349, 1238, '2014-5-5', NULL);
GO
USE Hospital
SELECT * FROM Physician
SELECT * FROM Patient
SELECT * FROM AdmissionDate
SELECT * FROM TreatmentDetails
SELECT Patient.PatientID, Patient.FirstName, Patient.LastName, Patient.DateOfBirth, AdmissionDate.AdmissionDate, AdmissionDate.DischargeDate, Physician.Specialty
FROM Patient, AdmissionDate, Physician
WHERE AdmissionDate IS NOT NULL
ORDER BY Patient.LastName, Patient.FirstName, AdmissionDate.AdmissionDate
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NOT NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName
I keep having an issue where I'm trying to load all my tables into a database.
Whenever I try load a table which references "paper_code" I keep getting problem errors, which then don't create the table.
I've been trying to nail out the errors and have got some papers loading, but it seems only the tables that reference papers(paper_code) are having issues.
code:
DROP TABLE contacts;
DROP TABLE gender;
DROP TABLE lecture_location;
DROP TABLE enrols;
DROP TABLE teaches;
DROP TABLE staff;
DROP TABLE student;
DROP TABLE papers;
DROP TABLE departments;
CREATE TABLE departments
(dept_id INT PRIMARY KEY,
dept_location VARCHAR2(25) NOT NULL,
dept_name VARCHAR2(25) NOT NULL);
INSERT INTO departments VALUES
(01, 'ALBANY STREET', 'COMPUTER SCIENCE');
INSERT INTO departments VALUES
(02, 'UNION STREET', 'MUSIC');
INSERT INTO departments VALUES
(03, 'HOWE STREET', 'ANATOMY');
INSERT INTO departments VALUES
(04, 'ANZAC AVENUE', 'THEATRE');
CREATE TABLE papers
(paper_code INT,
EFTS INT NOT NULL,
dept_id INT REFERENCES departments(dept_id),
PRIMARY KEY(paper_code, dept_id));
INSERT INTO papers VALUES
(160, 0.18, 01);
INSERT INTO papers VALUES
(241, 0.18, 02);
INSERT INTO papers VALUES
(344, 0.18, 03);
INSERT INTO papers VALUES
(444, 0.18, 04);
CREATE TABLE student
(student_id INT PRIMARY KEY,
fname CHAR(11) NOT NULL,
lname CHAR(11) NOT NULL,
degree CHAR(15) NOT NULL);
INSERT INTO student VALUES
(172384, 'Michael', 'McDonald', 'BSc');
INSERT INTO student VALUES
(849294, 'Matthew', 'Brockie', 'BA');
INSERT INTO student VALUES
(384583, 'Daniel', 'Anderson', 'BSc');
CREATE TABLE staff
(staff_id INT PRIMARY KEY,
dept_id INT REFERENCES departments(dept_id),
fname CHAR(15) NOT NULL,
lname CHAR(15) NOT NULL);
INSERT INTO staff VALUES
(31, 01, 'Tony', 'Michaels');
INSERT INTO staff VALUES
(32, 01, 'Steph', 'Cardy');
INSERT INTO staff VALUES
(33, 02, 'Alex', 'Freeland');
INSERT INTO staff VALUES
(34, 02, 'Sam', 'Stewart');
INSERT INTO staff VALUES
(35, 03, 'Monique', 'Cardy');
INSERT INTO staff VALUES
(36, 03, 'Bayan', 'Zach');
CREATE TABLE teaches
(paper_code INT,
staff_id INT REFERENCES staff(staff_id),
dept_id INT,
PRIMARY KEY(paper_code, staff_id, dept_id),
FOREIGN KEY (paper_code, dept_id) REFERENCES papers(paper_code, dept_id));
INSERT INTO teaches VALUES
(160, 32, 01);
INSERT INTO teaches VALUES
(241, 31, 01);
INSERT INTO teaches VALUES
(344, 33, 02);
INSERT INTO teaches VALUES
(241, 34, 03);
INSERT INTO teaches VALUES
(444, 35, 03);
INSERT INTO teaches VALUES
(444, 36, 04);
CREATE TABLE enrols
(paper_code INT REFERENCES papers(paper_code),
student_id INT REFERENCES student(student_id),
date_enrolled DATE,
PRIMARY KEY(paper_code, student_id));
INSERT INTO enrols VALUES
(160, 172384, TO_DATE('22-Mar-1994', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES
(444, 849294, TO_DATE('14-Jul-1992', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES
(444, 172384, TO_DATE('23-Mar-1992', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES
(160, 384583, TO_DATE('07-Aug-1992', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES --fix
(160, 172384, TO_DATE('30-Jul-1994', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES
(241, 849294, TO_DATE('08-Sep-1995', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES
(241, 384583, TO_DATE('25-Dec-1996', 'dd-mon-yyyy'));
CREATE TABLE lecture_location
(paper_code INT REFERENCES papers(paper_code),
dept_id INT REFERENCES departments(dept_id),
lecture_loc VARCHAR2(15),
PRIMARY KEY(paper_code, dept_id, lecture_loc));
INSERT INTO lecture_location VALUES
(160, 'ARCHWAY');
INSERT INTO lecture_location VALUES
(241, 'CASTLE');
CREATE TABLE gender
(student_id INT PRIMARY KEY REFERENCES student(student_id),
gender CHAR(9) NOT NULL);
INSERT INTO gender VALUES
(172384, 'Female');
INSERT INTO gender VALUES
(384583, 'Male');
CREATE TABLE contacts
(contact_details INT,
staff_id INT REFERENCES staff(staff_id),
PRIMARY KEY(contact_details, staff_id));
INSERT INTO contacts VALUES
(022017456, 31);
INSERT INTO contacts VALUES
(034737447, 31);
INSERT INTO contacts VALUES
(02285756, 32);
INSERT INTO contacts VALUES
(034735858, 32);
INSERT INTO contacts VALUES
(034552097, 33);
INSERT INTO contacts VALUES
(022867385, 33);
INSERT INTO contacts VALUES
(021495939, 34);
INSERT INTO contacts VALUES
(034993872, 35);
INSERT INTO contacts VALUES
(027459278, 36);
COMMIT;
All the tables except the ones refering paper_code are working.
Errors are:
INSERT INTO teaches VALUES
*
ERROR at line 1:
ORA-02291: integrity constraint (DAANDERSON.SYS_C00623423) violated - parent
key not found
For enrols:
(paper_code INT REFERENCES papers(paper_code),
*
ERROR at line 2:
ORA-02270: no matching unique or primary key for this column-list
For lecture_location
(paper_code INT REFERENCES papers(paper_code),
*
ERROR at line 2:
ORA-02270: no matching unique or primary key for this column-list
Been trying for a few hours and stil can't get to work. Any information appreciated!
When creating your table teaches, you have:
FOREIGN KEY (paper_code, dept_id) REFERENCES papers(paper_code, dept_id));
So every (paper_code, dept_id) must exist as (paper_code, dept_id) in papers.
Your 2nd entry (241, 01) does not exist, nor does your fourth value (241, 03).
(others may be missing, I didn't check them all)
You're also not inserting dept_id values into lecture_location
You have a primary key value duplicated in enrols:
(160, 172384)
This part of enrols:
CREATE TABLE enrols
(paper_code INT REFERENCES papers(paper_code),
is invalid, since you must reference a unique foreign key - and the only unique key on papers is its primary key of (paper_code, dept_id)
Ditto for this part of lecture_location:
(paper_code INT REFERENCES papers(paper_code),
On the bright side, after doing the fixes above the schema actually builds: http://sqlfiddle.com/#!4/5ed2c2
Table LPTitle:
CREATE TABLE LPTitle(
title VARCHAR(30) NOT NULL, /* Position title */
CONSTRAINT LPTitle_pkey PRIMARY KEY ( title ) );
INSERT INTO LPTitle VALUES( 'ASSISTANT' );
INSERT INTO LPTitle VALUES( 'ASSOC. LECTURER' );
INSERT INTO LPTitle VALUES( 'LECTURER' );
INSERT INTO LPTitle VALUES( 'SENIOR LECTURER' );
INSERT INTO LPTitle VALUES( 'ASSOC. PROFESSOR' );
INSERT INTO LPTitle VALUES( 'PROFESSOR' );
Table Position:
CREATE TABLE Position(
p# NUMBER(8) NOT NULL, /* Position number */
ptitle VARCHAR(30) NOT NULL, /* Position title */
employer VARCHAR(100) NOT NULL, /* Institution name */
salary NUMBER(9,2) NOT NULL, /* Salary */
extras VARCHAR(50) , /* Extras */
specification LONG , /* Specification */
CONSTRAINT Position_pkey PRIMARY KEY ( p# ),
CONSTRAINT Position_fkey1 FOREIGN KEY ( ptitle )
REFERENCES LPTitle ( title ) );
INSERT INTO Position VALUES ( 00000001, 'LECTURER', 'UNSW', 45000.00, 'computer', 'Teaching');
INSERT INTO Position VALUES ( 00000002, 'LECTURER', 'UOW', 450000.00, 'mouse pad', 'Research');
INSERT INTO Position VALUES ( 00000003, 'SENIOR LECTURER', 'UTS', 50000.00, NULL, 'A lot of hard work' );
INSERT INTO Position VALUES ( 00000004, 'ASSOC. PROFESSOR', 'UOW', 60000.00, NULL, NULL);
INSERT INTO Position VALUES ( 00000005, 'PROFESSOR', 'UQ', 80000.00, 'chair', 'Research' );
INSERT INTO Position VALUES ( 00000006, 'PROFESSOR', 'UNSW', 80000.00, 'chair', 'Research' );
INSERT INTO Position VALUES ( 00000007, 'PROFESSOR', 'UOW', 80000.00, 'chair', 'Teaching and research');
Table Applies:
CREATE TABLE Applies(
a# NUMBER(6) NOT NULL, /* Applicant number */
p# NUMBER(8) NOT NULL, /* Position number */
appdate DATE NOT NULL, /* Application date */
CONSTRAINT Applies_pkey PRIMARY KEY ( a#, p# ),
CONSTRAINT Applies_fkey1 FOREIGN KEY ( a# )
REFERENCES Applicant ( a# )
ON DELETE CASCADE,
CONSTRAINT Applies_fkey2 FOREIGN KEY ( p# )
REFERENCES Position ( p# )
ON DELETE CASCADE);
INSERT INTO Applies VALUES( 000001, 00000001, TO_DATE('13-DEC-1999','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000002, 00000001, TO_DATE('13-DEC-1999','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000003, 00000002, TO_DATE('14-NOV-1999','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000004, 00000002, TO_DATE('20-JAN-2000','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000005, 00000002, TO_DATE('22-JAN-2000','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000005, 00000003, TO_DATE('09-MAY-1999','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000006, 00000003, TO_DATE('17-JUN-1999','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000007, 00000003, TO_DATE('18-JUN-1999','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000007, 00000004, TO_DATE('13-APR-2000','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000008, 00000004, TO_DATE('13-APR-2000','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000009, 00000004, TO_DATE('14-APR-2000','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000010, 00000005, TO_DATE('23-SEP-1999','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000001, 00000006, TO_DATE('26-OCT-1999','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000002, 00000006, TO_DATE('27-OCT-1999','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000003, 00000006, TO_DATE('28-OCT-1999','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000004, 00000007, TO_DATE('01-JAN-2000','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000005, 00000007, TO_DATE('03-JAN-2000','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000006, 00000007, TO_DATE('04-JAN-2000','DD-MON-YYYY') );
INSERT INTO Applies VALUES( 000007, 00000007, TO_DATE('07-JAN-2000','DD-MON-YYYY') );
With the 3 tables above, I want to find the titles of all positions that have no applications. How to implements this by using SELECT statements with one or more NOT EXISTS clauses?
This is the query I have so far, the result is always "no rows selected" (which is wrong):
SELECT
LPTitle.title
FROM
LPTitle
FULL OUTER JOIN
Position
ON
LPTitle.title = Position.ptitle
WHERE
NOT EXISTS
(
SELECT Applies.p# FROM Applies INNER JOIN Position ON Applies.p# = Position.p#
)
;
I think the query below will do the job. Please note that you don't need the LPTitle table, as you already have all title values stored in Position tables ptitle column.
Basicly the result is the same: you have an application for all of your 7 positions!
SELECT
p.ptitle
FROM
Position p
WHERE
NOT EXISTS
(
SELECT 1 FROM Applies WHERE p# = p.p#
)
;
If you meant to look for all unused titles, than that's another task:
SELECT
l.title
FROM
LPTitle l
WHERE
NOT EXISTS
(
SELECT 1 FROM Position ptitle = l.title
)
;
I have multiple possible data tables (created to support parallel processing) to search against to find a match, and another table containing entries to exclude. The tables are defined as follows, along with some example data:
CREATE TABLE HOUSEHOLD_1
(
PERSON_ID NUMBER NOT NULL ENABLE,
HOUSEHOLD_HEAD_ID NUMBER NOT NULL ENABLE,
RELATIONSHIP CHAR (1) NOT NULL ENABLE,
CONSTRAINT HOUSEHOLD_1_PK PRIMARY KEY (PERSON_ID, HOUSEHOLD_HEAD_ID, RELATIONSHIP) ENABLE
);
INSERT INTO HOUSEHOLD_1 VALUES (1, 1, 'H');
INSERT INTO HOUSEHOLD_1 VALUES (2, 1, 'S');
INSERT INTO HOUSEHOLD_1 VALUES (3, 1, 'D');
CREATE TABLE HOUSEHOLD_2
(
PERSON_ID NUMBER NOT NULL ENABLE,
HOUSEHOLD_HEAD_ID NUMBER NOT NULL ENABLE,
RELATIONSHIP CHAR (1) NOT NULL ENABLE,
CONSTRAINT HOUSEHOLD_2_PK PRIMARY KEY (PERSON_ID, HOUSEHOLD_HEAD_ID, RELATIONSHIP) ENABLE
);
INSERT INTO HOUSEHOLD_2 VALUES (4, 4, 'H');
INSERT INTO HOUSEHOLD_2 VALUES (5, 4, 'S');
INSERT INTO HOUSEHOLD_2 VALUES (6, 4, 'D');
CREATE TABLE HOUSEHOLD_3
(
PERSON_ID NUMBER NOT NULL ENABLE,
HOUSEHOLD_HEAD_ID NUMBER NOT NULL ENABLE,
RELATIONSHIP CHAR (1) NOT NULL ENABLE,
CONSTRAINT HOUSEHOLD_3_PK PRIMARY KEY (PERSON_ID, HOUSEHOLD_HEAD_ID, RELATIONSHIP) ENABLE
);
INSERT INTO HOUSEHOLD_3 VALUES (7, 7, 'H');
INSERT INTO HOUSEHOLD_3 VALUES (8, 7, 'S');
INSERT INTO HOUSEHOLD_3 VALUES (9, 7, 'D');
CREATE TABLE HOUSEHOLD_DELETIONS
(
PERSON_ID NUMBER NOT NULL ENABLE,
HOUSEHOLD_HEAD_ID NUMBER NOT NULL ENABLE,
RELATIONSHIP CHAR (1) NOT NULL ENABLE,
CONSTRAINT HOUSEHOLD_DELETIONS_PK PRIMARY KEY (PERSON_ID, HOUSEHOLD_HEAD_ID, RELATIONSHIP) ENABLE
);
INSERT INTO HOUSEHOLD_DELETIONS VALUES (9, 7, 'D');
CREATE TABLE CLOSED_ACCOUNTS
(
PERSON_ID NUMBER NOT NULL ENABLE,
CONSTRAINT CLOSED_ACCOUNTS_PK PRIMARY KEY (PERSON_ID) ENABLE
);
INSERT INTO CLOSED_ACCOUNTS VALUES (3);
INSERT INTO CLOSED_ACCOUNTS VALUES (6);
INSERT INTO CLOSED_ACCOUNTS VALUES (9);
INSERT INTO CLOSED_ACCOUNTS VALUES (10);
I need to find the PERSON_ID values in CLOSED_ACCOUNTS that have a matching PERSON_ID in either HOUSEHOLD_1, HOUSEHOLD_2, or HOUSEHOLD_3, but do not have a PERSON_ID in HOUSEHOLD_DELETIONS. With the data above, I should only find PERSON_ID values 3 and 6. I've tried the SQL tricks I know, but I have not been successful, so any assistance would be appreciated. Thanks in advance.
SET operations should work to you:
SQL> select person_id from CLOSED_ACCOUNTS
2 intersect (
3 select person_id from HOUSEHOLD_1
4 union
5 select person_id from HOUSEHOLD_2
6 union
7 select person_id from HOUSEHOLD_3
8 )
9 minus
10 select person_id from HOUSEHOLD_DELETIONS
11 /
PERSON_ID
----------
3
6