SELECT statements with one or more NOT EXISTS clauses - sql

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
)
;

Related

AVG() inside LISTAGG()

I need to group two columns, one of them with an average, AVG() inside an LISTAGG().
I have the following code:
CREATE OR REPLACE VIEW countryTimes AS
SELECT
LISTAGG(claOL.odCode||'-'||(AVG(claOL.timeCla) GROUP BY(claOl.timeCla))) WITHIN GROUP (ORDER BY c.cCode) AS ProvaTempsMig,
c.cDescription AS País,
c.cCode AS CodiPaís
FROM countries c
JOIN athletes a ON c.cCode = a.country
JOIN classificationOL claOL ON a.idCode = claOL.idAth;
But this throws this error:
ORA-00907: missing right parenthiesis erecho 00907. 00000 - "missing right parenthesis" *Cause: *Action:
I'm using Oracle.
UPDATE:
What I need to do is create a view where appears cCode, cDescription and a last column with the AVG of all the times for a single country. So I need to create from multiple rows, a single row for each country.
Code:
CREATE TABLE Countries (
cCode VARCHAR(5) NOT NULL,
cdescription VARCHAR(100) NOT NULL,
CONSTRAINT couPK PRIMARY KEY (cCode)
);
CREATE TABLE athletes (
idCode NUMBER NOT NULL,
Name VARCHAR(200) NOT NULL,
Surname VARCHAR(200) NOT NULL,
country VARCHAR(5) NOT NULL,
CONSTRAINT athPK PRIMARY KEY (idCode),
CONSTRAINT countryFK FOREIGN KEY (country) REFERENCES Countries (cCode)
);
CREATE TABLE olympicDisciplines (
oCode VARCHAR(10) NOT NULL,
odName VARCHAR(200) NOT NULL,
discipline VARCHAR(200) NOT NULL,
CONSTRAINT olympicPK PRIMARY KEY (oCode)
);
CREATE TABLE classificationOL(
idAth NUMBER NOT NULL,
odCode VARCHAR(10) NOT NULL,
timeCla INTEGER,
CONSTRAINT classifPK PRIMARY KEY (idAth, odCode),
CONSTRAINT claAthFK FOREIGN KEY (idAth) REFERENCES athletes (idCode),
CONSTRAINT claDFK FOREIGN KEY (odCode) REFERENCES olympicDisciplines (oCode)
);
UPDATE 2:
Data:
INSERT INTO Countries VALUES ('UK', 'United Kingdom');
INSERT INTO Countries VALUES ('AND', 'Andorra');
INSERT INTO Countries VALUES ('FR', 'France');
INSERT INTO athletes VALUES (1, 'Jack', 'Johnson', 'UK');
INSERT INTO athletes VALUES (2, 'Pau', 'Márquez', 'AND');
INSERT INTO athletes VALUES (3, 'Pierre', 'Dubois', 'FR');
INSERT INTO athletes VALUES (4, 'Christophe', 'Dubois', 'FR');
INSERT INTO athletes VALUES (5, 'Adolphe', 'Moreau', 'FR');
INSERT INTO olympicDisciplines VALUES ('ATH', 'Athletics', 'Athletics');
INSERT INTO olympicDisciplines VALUES ('CYC', 'Cycling', 'Cycling');
INSERT INTO olympicDisciplines VALUES ('CCC', 'Cycling CC', 'Cross Country Cycling');
INSERT INTO classificationOL VALUES (1, 'ATH', 120);
INSERT INTO classificationOL VALUES (2, 'ATH', 119);
INSERT INTO classificationOL VALUES (3, 'CCC', 38);
INSERT INTO classificationOL VALUES (4, 'CCC', 37);
INSERT INTO classificationOL VALUES (5, 'ATH', 122);
Reading your first UPDATE, if you're allowed to, you can transform your tables to object to solve your necessity, instead of using LISTAGG(). I'll show you:
CREATE TYPE average AS OBJECT(
name VARCHAR(200),
avgerageTime NUMBER);
CREATE TYPE results AS TABLE OF average;
CREATE TYPE countriesResults AS OBJECT(
cName VARCHAR(100),
cCode VARCHAR(5),
classifications results
);
CREATE VIEW countriesAverages OF countriesResults
WITH OBJECT OID (coName)
AS
SELECT c.cdescription, c.ccode,
CAST (MULTISET (SELECT
olympicDisciplines.name, avg(classificationOL.timeCla)
FROM athletes a, countries, classificationOL, olympicDisciplines
WHERE countries.cCode = c.cCode
AND a.idCode = classificationOL.idAth
AND a.country = countries.cCode
AND olympicdisciplines.oCode = classificationOL.oCode
GROUP BY olympicdisciplines.odName) AS results )
FROM countries c;

Using multiple foreign keys in a SQL select statement

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

SQL Developer - Integrity Constraint , parent key not found ( while inserting values )

I know that in order to insert values in a table which relies on foreign keys you need to have data in that primary key of that table .
These are my constraints :
ALTER TABLE DIDACT
MODIFY (CONSTRAINT id_prof_fk FOREIGN KEY(id_prof) REFERENCES profs (id_prof));
ALTER TABLE DIDACT
MODIFY (CONSTRAINT id_course_fk FOREIGN KEY(id_course) REFERENCES courses (id_course));
Next I insert values in both profs and courses tables :
INSERT INTO courses VALUES ('21', 'Logic', 1, 1, 5);
INSERT INTO courses VALUES ('22', 'Math', 1, 1, 4);
INSERT INTO courses VALUES ('23', 'OOP', 1, 2, 5);
INSERT INTO courses VALUES ('24', 'DB', 2, 1, 8);
INSERT INTO courses VALUES ('25', 'Java', 2, 2, 5);
INSERT INTO profs VALUES ('p1', 'Mary', 'Banks', 'Prof');
INSERT INTO profs VALUES ('p2', 'Francis', 'Steven', 'Conf');
INSERT INTO profs VALUES ('p3', 'John', 'Jobs', 'Prof');
INSERT INTO profs VALUES ('p4', 'Alex', 'Brown', 'Prof');
INSERT INTO profs VALUES ('p5', 'Dan', 'Lovelace', 'Lect');
INSERT INTO profs VALUES ('p6', 'Roxanne', 'Smith', 'Conf');
Then I'm trying to populate the DIDACT table:
INSERT INTO didact VALUES ('p1','21');
INSERT INTO didact VALUES ('p3','21');
INSERT INTO didact VALUES ('p5','22');
But this occurs :
INSERT INTO didact VALUES ('p1','21') Error report - SQL Error:
ORA-02291: integrity constraint (user.ID_COURSE_FK) violated - parent
key not found
02291. 00000 - "integrity constraint (%s.%s) violated - parent key not found"
*Cause: A foreign key value has no matching primary key value.
*Action: Delete the foreign key or add a matching primary key.
These are my tables , in case it will help :
CREATE TABLE courses(
id_course CHAR(2),
course_name VARCHAR2(15),
year NUMBER(1),
semester NUMBER(1),
credits NUMBER(2)
)
CREATE TABLE profs(
id_prof CHAR(4),
name CHAR(10),
surname CHAR(10),
grade VARCHAR2(5)
)
CREATE TABLE didact(
id_prof CHAR(4),
id_course CHAR(4)
)
I'm struggling with this for about an hour and I still haven't managed to find my mistake.
Thank you.
You seem to have different formats for id_course in your tables. In didact it's id_course CHAR(4) and in courses it's id_course CHAR(2).
And since you use a fixed-length type the value in didact will differ from the one in courses by two added blanks.

Microsoft SQL Server

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

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

create table pilot (
emp_num int,
pl_license varchar (3),
pl_ratings varchar (30),
pl_med_type int,
pl_med_date date,
pl_pt135_date date,
constraint PK_pilot primary key (emp_num)
)
insert into pilot(emp_num,pl_license,pl_ratings,pl_med_type,pl_med_date,pl_pt135_date)
values (101,'ATP','SEL/MEL/instr/CFII',1,12-4-2005,15-6-2005)
insert into pilot(emp_num,pl_license,pl_ratings,pl_med_type,pl_med_date,pl_pt135_date)
values (104,'ATP','SEL/MEL/instr',1,10-5-2005,23-3-2006)
insert into pilot(emp_num,pl_license,pl_ratings,pl_med_type,pl_med_date,pl_pt135_date)
values (105,'COM','SEL/MEL/instr/CFI',2,25-2-2006,12-2-2005)
insert into pilot(emp_num,pl_license,pl_ratings,pl_med_type,pl_med_date,pl_pt135_date)
values (106,'COM','SEL/MEL/instr',2,02-4-2006,24-12-2005)
insert into pilot(emp_num,pl_license,pl_ratings,pl_med_type,pl_med_date,pl_pt135_date)
values (109,'COM','SEL/MEL/instr/CFII',1,14-4-2006,21-4-2006)
My question is there is an error in every insert
Operand type clash: int is incompatible with date
How to fix this?
Also here ...
create table employee (
emp_num int,
constraint PK_employee primary key (emp_num),
foreign key(emp_num) references pilot(emp_num),
emp_title varchar (4),
emp_lname varchar (20),
emp_fname varchar (30),
emp_initial varchar (2),
emp_dob date,
emp_hire_date date,
)
insert into employee(emp_num,emp_title,emp_lname,emp_fname,emp_initial,emp_dob,emp_hire_date)
values (100,'Mr.','Kolmycz','George','D',15-5-1942,15-3-1987)
insert into employee(emp_num,emp_title,emp_lname,emp_fname,emp_initial,emp_dob,emp_hire_date)
values (101,'Ms.','Lewis','Rhonda','G',19-3-1965,25-4-1988)
insert into employee(emp_num,emp_title,emp_lname,emp_fname,emp_initial,emp_dob,emp_hire_date)
values (102,'Mr.','Vandam','Rhett',' ',14-11-1958,20-12-1992)
insert into employee(emp_num,emp_title,emp_lname,emp_fname,emp_initial,emp_dob,emp_hire_date)
values (103,'Ms.','Jones','Anne','M',16-10-1974,28-8-2005)
insert into employee(emp_num,emp_title,emp_lname,emp_fname,emp_initial,emp_dob,emp_hire_date)
values (104,'Mr.','Lange','John','P',08-11-1971,20-10-1996)
insert into employee(emp_num,emp_title,emp_lname,emp_fname,emp_initial,emp_dob,emp_hire_date)
values (105,'Mr.','williams','Robert','D',14-3-1975,08-1-2006)
insert into employee(emp_num,emp_title,emp_lname,emp_fname,emp_initial,emp_dob,emp_hire_date)
values (106,'Mrs.','Duzak','Jeanine','K',12-2-1968,05-1-1991)
insert into employee(emp_num,emp_title,emp_lname,emp_fname,emp_initial,emp_dob,emp_hire_date)
values (107,'Mr.','Diante','Jorge','D',21-8-1974,05-1-1991)
insert into employee(emp_num,emp_title,emp_lname,emp_fname,emp_initial,emp_dob,emp_hire_date)
values (108,'Mr.','Wlesenbach','Paul','R',14-2-1966,18-11-1994)
insert into employee(emp_num,emp_title,emp_lname,emp_fname,emp_initial,emp_dob,emp_hire_date)
values (109,'Ms.','Travis','Elizabeth','K',18-6-1961,14-4-1991)
insert into employee(emp_num,emp_title,emp_lname,emp_fname,emp_initial,emp_dob,emp_hire_date)
values (110,'Mrs.','Genkazi','Leighla','W',19-5-1970,01-12-1992)
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__crew__emp_num__0F975522". The conflict occurred in database "melisa", table "dbo.employee", column 'emp_num'. error on
this table
create table earndrating(
emp_num int,
constraint PK_earndarating primary key(emp_num, rtg_code),
rtg_code varchar(6),
foreign key (emp_num) references pilot(emp_num),
foreign key(rtg_code) references rating(rtg_code),
earningth_date varchar(20),
)
insert into earndrating(emp_num,rtg_code,earningth_date)
values(101,'CFI','18-Feb-98' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(101,'CFII','14-Dec-05' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(101,'INSTR','08-Nov-93' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(101,'MEL','23-Jun-94' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(101,'SEL','21-Apr-93' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(104,'INSTR','14-Jul-96' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(104,'MEL','29-Jan-97' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(104,'SEL','12-Mar-95' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(105,'CFI','18-Nov-97' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(105,'INSTR','17-Apr-95' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(105,'MEL','12-Aug-95' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(105,'SEL','23-Sep-94' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(106,'INSTR','20-Dec-95' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(106,'MEL','02-Apr-95' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(105,'SEL','10-Mar-94' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(109,'CFI','05-Nov-98' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(109,'CFII','21-Jun-03' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(109,'INSTR','23-Jul-96' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(109,'MEL','15-Marc-97' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(109,'SEL','05-Feb-96' )
insert into earndrating(emp_num,rtg_code,earningth_date)
values(109,'SES','12-May-96' )
This expression 12-4-2005 is a calculated int and the value is -1997. You should do like this instead '2005-04-12' with the ' before and after.
Try wrapping your dates in single quotes, like this:
'15-6-2005'
It should be able to parse the date this way.
FYI this turned out to be an issue for me where I had two tables in a statement like the following:
SELECT * FROM table1
UNION ALL
SELECT * FROM table2
It worked, but then somewhere along the line the order of columns in one of the table definitions got changed. Changing the * to SELECT column1, column2 fixed the issue. No idea how that happened, but lesson learned!
I had the same problem. I tried 'yyyy-mm-dd' format i.e. '2013-26-11' and got rid of this problem...
INSERT INTO EMPLOYEINFO VALUES
(1, 'Sanjay', 'Mehra', 'HR', 'P1', 'Hyderabad(HYD)', '01/12/1976', 'M'),
(2, 'Ananya', 'Mishra', 'Admin', 'P2', 'Delhi(DEL)', '02/05/1968', 'F'),
(3, 'Rohan', 'Diwan', 'Account', 'P3', 'Mumbai(BOM)', '01/01/1980', 'M'),
(4, 'Sonia', 'Kulkarni', 'HR', 'P1', 'Hyderabad(Hyd)', '02/05/1992', 'F'),
(5, 'Ankit', 'Kapoor', 'Admin', 'P2', 'Delhi(DEL)', '03/07/1994', 'M');
if you are getting this [Operand type clash: int is incompatible with date]
error then just add your dates in single qoutes ''.
the format is ('MM-DD-YYYY') for the date