What is wrong with my queries? - sql

All the code is correct but the queries (which are at the very bottom) don't seem to run. I checked on w3schools.com for more information, but it seems like there's nothing wrong with my code.
Can anyone take a look and explain?
--Drop tables--
DROP TABLE Job;
DROP TABLE Employee;
DROP TABLE Purchase;
DROP TABLE SoccerBall;
DROP TABLE Client;
--Create tables--
CREATE TABLE Client
(
ClientId INT NOT NULL,
ClientName VARCHAR(20) NOT NULL,
Street VARCHAR(20) NOT NULL,
City VARCHAR(20) NOT NULL,
ZipCode VARCHAR(5) NOT NULL,
Phone VARCHAR(15) NULL,
EmailAddr VARCHAR(50) NULL,
PRIMARY KEY(ClientId)
);
CREATE TABLE SoccerBall
(
BallId INT NOT NULL,
BallSize NUMBER(1) NOT NULL,
Color VARCHAR(20) NOT NULL,
Material VARCHAR(20) NOT NULL,
PRIMARY KEY(BallId)
);
CREATE TABLE Purchase
(
PurchaseId INT NOT NULL,
ClientId INT NOT NULL,
BallId INT NOT NULL,
PurchaseDate DATE NOT NULL,
PRIMARY KEY (PurchaseId),
FOREIGN KEY (ClientId) REFERENCES Client (ClientId),
FOREIGN KEY (BallId) REFERENCES SoccerBall (BallId)
);
CREATE TABLE Employee
(
EmployeeId INT NOT NULL,
EmployeeName VARCHAR(50) NOT NULL,
PRIMARY KEY (EmployeeId)
);
CREATE TABLE Job
(
JobId INT NOT NULL,
PurchaseId INT NOT NULL,
EmployeeId INT NOT NULL,
AssignDate DATE NOT NULL,
PRIMARY KEY (JobId),
FOREIGN KEY (EmployeeId) REFERENCES Employee (EmployeeId)
);
--Insert data--
INSERT INTO Client VALUES
(1, 'Adidas', '123 Adidas Lane', 'Adida', '22209', '1-800-555-1987', 'corporate#adidas.com');
INSERT INTO Client VALUES
(2, 'Nike', '234 Nike Drive', 'Nikail', '22182', '1-888-555-9876', 'corporate#nike.com');
INSERT INTO Client VALUES
(3, 'Puma', '345 Puma Blvd', 'Puma City', '20912', '1-800-555-6247', 'corporate#puma.com');
INSERT INTO Client VALUES
(4, 'Reebok', '456 Reebok Cove', 'Old Reebok', '20902', '1-800-555-1000', 'corporate#reebok.com');
INSERT INTO Client VALUES
(5, 'Vans', '567 Vans Lane', 'Vancouver', '20725', '1-900-666-2000', 'corporate#vans.com');
INSERT INTO Client VALUES
(6, 'Jordan', '234 Nike Drive', 'Nikail', '22182', '1-888-555-8765', 'corporate#jordan.com');
INSERT INTO Client VALUES
(7, 'Diadora', '345 Puma Blvd', 'Puma City', '20912', '1-800-555-4126', 'corporate#diadora.com');
INSERT INTO SoccerBall VALUES
(11, 1, 'blue', 'felt');
INSERT INTO SoccerBall VALUES
(12, 3, 'red', 'leather');
INSERT INTO SoccerBall VALUES
(13, 3, 'yellow', 'faux leather');
INSERT INTO SoccerBall VALUES
(14, 5, 'black', 'leather');
INSERT INTO SoccerBall VALUES
(15, 4, 'white', 'faux leather');
INSERT INTO SoccerBall VALUES
(16, 3, 'purple', 'rubber');
INSERT INTO SoccerBall VALUES
(17, 1, 'blue', 'faux leather');
INSERT INTO Purchase VALUES
(21, 2, 11, DATE '2013-01-01');
INSERT INTO Purchase VALUES
(22, 4, 12, DATE '2012-03-24');
INSERT INTO Purchase VALUES
(23, 7, 15, DATE '2013-05-01');
INSERT INTO Purchase VALUES
(24, 5, 13, DATE '2005-12-30');
INSERT INTO Purchase VALUES
(25, 6, 16, DATE '1999-01-23');
INSERT INTO Employee VALUES
(111, 'Vivin Viswanathan');
INSERT INTO Employee VALUES
(222, 'Andy Edwards');
INSERT INTO Employee VALUES
(333, 'Frank Hellwig');
INSERT INTO Employee VALUES
(444, 'Vandana Janeja');
INSERT INTO Job VALUES
(1111, 21, 111, DATE '2013-01-02');
INSERT INTO Job VALUES
(5555, 22, 111, DATE '2012-03-26');
INSERT INTO Job VALUES
(2222, 23, 222, DATE '2013-05-08');
INSERT INTO Job VALUES
(3333, 24, 222, DATE '2006-01-02');
INSERT INTO Job VALUES
(4444, 25, 111, DATE '1999-01-30');
--Queries--
--Query 1--Show me the information in the database
SELECT * FROM Client;
SELECT * FROM SoccerBall;
SELECT * FROM Purchase;
SELECT * FROM Employee;
SELECT * FROM Job;
--"Forgot" Quantity Attribute. Adding that--
ALTER TABLE Purchase ADD Quantity NUMBER(5);
UPDATE Purchase SET Quantity = '12000' WHERE ClientId = '1';
UPDATE Purchase SET Quantity = '2492' WHERE ClientId = '2';
UPDATE Purchase SET Quantity = '94203' WHERE ClientId = '3';
UPDATE Purchase SET Quantity = '4394' WHERE ClientId = '4';
UPDATE Purchase SET Quantity = '0' WHERE ClientId = '5';
UPDATE Purchase SET Quantity = '4832' WHERE ClientId = '6';
UPDATE Purchase SET Quantity = '10002' WHERE ClientId = '7';
SELECT * FROM Purchase;
--Queries Continued--
--Query 2--I want to know how many clients we have
SELECT COUNT(*) FROM Client;
--Query 3--Which client ordered the most soccer balls?***********
SELECT MAX(Quantity), ClientName
FROM Purchase P, Client C
WHERE P.ClientId = C.ClientId;
--Query 4--How many projects does each employe have?***********
SELECT EmployeeId COUNT(*)
FROM Job
GROUP BY EmployeeId;
--Query 5--First purchases, first served. Show me the order of the purchases by date***********
SELECT ClientName, PurchaseDate
FROM Purchase P, Client C
WHERE P.ClientId = C.ClientId AND ORDER BY PurchaseDate;
--Query 6--Show me what kind of balls were purchased***********
SELECT B.BallId, B.BallSize, B.Color, B.Material
FROM SoccerBall B, Purchase P, Client C
WHERE P.ClientId = C.ClientId AND P.BallId = B.BallId AND C.ClientId = 1;
--Query 7--Show me who purchased what balls**************
SELECT B.BallId, B.BallSize, B.Color, B.Material, C.ClientId, ClientName
FROM SoccerBall B, Purchase P, Client C
WHERE P.ClientId = C.ClientId AND P.BallId = B.BallId GROUP BY ClientName;
Thanks so much!

You have several issues with your queries.
Query 3 is missing a GROUP BY with the aggregate function:
SELECT MAX(Quantity), ClientName
FROM Purchase P
INNER JOIN Client C
ON P.ClientId = C.ClientId
GROUP BY ClientName;
Query 4 is missing a comma between the columns employeeId and count(*):
SELECT EmployeeId, COUNT(*)
FROM Job
GROUP BY EmployeeId;
Query 5 has an errant AND before the ORDER BY:
SELECT ClientName, PurchaseDate
FROM Purchase P
INNER JOIN Client C
ON P.ClientId = C.ClientId
ORDER BY PurchaseDate;
Query 6 is you want all of the balls purchased, I don't think you want a filter on ClientId:
SELECT B.BallId, B.BallSize, B.Color, B.Material
FROM SoccerBall B
INNER JOIN Purchase P
ON P.BallId = B.BallId
INNER JOIN Client C
ON P.ClientId = C.ClientId;
Query 7 is using a GROUP BY on one column only which will not work correctly:
SELECT B.BallId, B.BallSize, B.Color, B.Material, C.ClientId, ClientName
FROM SoccerBall B
INNER JOIN Purchase P
ON P.BallId = B.BallId
INNER JOIN Client C
ON P.ClientId = C.ClientId;
See SQL Fiddle with Demo.
As a side note, you will notice that I updated the queries to use INNER JOIN syntax instead of commas between the tables and the joins in the WHERE clause.

This one works. Try it out.
' --Drop tables--
DROP TABLE job;
DROP TABLE employee;
DROP TABLE purchase;
DROP TABLE soccerball;
DROP TABLE client;
--Create tables--
CREATE TABLE client
(
clientid INT NOT NULL IDENTITY(1, 1),
clientname VARCHAR(20) NOT NULL,
street VARCHAR(20) NOT NULL,
city VARCHAR(20) NOT NULL,
zipcode VARCHAR(5) NOT NULL,
phone VARCHAR(15) NULL,
emailaddr VARCHAR(50) NULL,
PRIMARY KEY(clientid)
);
CREATE TABLE soccerball
(
ballid INT NOT NULL,
ballsize NUMERIC(1) NOT NULL,
color VARCHAR(20) NOT NULL,
material VARCHAR(20) NOT NULL,
PRIMARY KEY(ballid)
);
CREATE TABLE purchase
(
purchaseid INT NOT NULL,
clientid INT NOT NULL,
ballid INT NOT NULL,
purchasedate DATETIME NOT NULL,
PRIMARY KEY (purchaseid),
FOREIGN KEY (clientid) REFERENCES client (clientid),
FOREIGN KEY (ballid) REFERENCES soccerball (ballid)
);
CREATE TABLE employee
(
employeeid INT NOT NULL,
employeename VARCHAR(50) NOT NULL,
PRIMARY KEY (employeeid)
);
CREATE TABLE job
(
jobid INT NOT NULL,
purchaseid INT NOT NULL,
employeeid INT NOT NULL,
assigndate DATETIME NOT NULL,
PRIMARY KEY (jobid),
FOREIGN KEY (employeeid) REFERENCES employee (employeeid)
)
--Insert data--
INSERT INTO dbo.client
(clientname,
street,
city,
zipcode,
phone,
emailaddr)
VALUES ( 'Adidas',
'123 Adidas Lane',
'Adida',
'22209',
'1-800-555-1987',
'corporate#adidas.com')
INSERT INTO client
(clientname,
street,
city,
zipcode,
phone,
emailaddr)
VALUES ('Nike',
'234 Nike Drive',
'Nikail',
'22182',
'1-888-555-9876',
'corporate#nike.com')
INSERT INTO client
VALUES ( 'Puma',
'345 Puma Blvd',
'Puma City',
'20912',
'1-800-555-6247',
'corporate#puma.com')
INSERT INTO client
VALUES ( 'Reebok',
'456 Reebok Cove',
'Old Reebok',
'20902',
'1-800-555-1000',
'corporate#reebok.com')
INSERT INTO client
VALUES ( 'Vans',
'567 Vans Lane',
'Vancouver',
'20725',
'1-900-666-2000',
'corporate#vans.com')
INSERT INTO client
VALUES ( 'Jordan',
'234 Nike Drive',
'Nikail',
'22182',
'1-888-555-8765',
'corporate#jordan.com')
INSERT INTO client
VALUES ( 'Diadora',
'345 Puma Blvd',
'Puma City',
'20912',
'1-800-555-4126',
'corporate#diadora.com')
INSERT INTO soccerball
VALUES (11,
1,
'blue',
'felt');
INSERT INTO soccerball
VALUES (12,
3,
'red',
'leather');
INSERT INTO soccerball
VALUES (13,
3,
'yellow',
'faux leather');
INSERT INTO soccerball
VALUES (14,
5,
'black',
'leather');
INSERT INTO soccerball
VALUES (15,
4,
'white',
'faux leather');
INSERT INTO soccerball
VALUES (16,
3,
'purple',
'rubber');
INSERT INTO soccerball
VALUES (17,
1,
'blue',
'faux leather');
INSERT INTO purchase
VALUES (21,
2,
11,
'2013-01-01');
INSERT INTO purchase
VALUES (22,
4,
12,
'2012-03-24');
INSERT INTO purchase
VALUES (23,
7,
15,
'2013-05-01');
INSERT INTO purchase
VALUES (24,
5,
13,
'2005-12-30');
INSERT INTO purchase
VALUES (25,
6,
16,
'1999-01-23');
INSERT INTO employee
VALUES (111,
'Vivin Viswanathan');
INSERT INTO employee
VALUES (222,
'Andy Edwards');
INSERT INTO employee
VALUES (333,
'Frank Hellwig');
INSERT INTO employee
VALUES (444,
'Vandana Janeja');
INSERT INTO job
VALUES (1111,
21,
111,
'2013-01-02');
INSERT INTO job
VALUES (5555,
22,
111,
'2012-03-26');
INSERT INTO job
VALUES (2222,
23,
222,
'2013-05-08');
INSERT INTO job
VALUES (3333,
24,
222,
'2006-01-02');
INSERT INTO job
VALUES (4444,
25,
111,
'1999-01-30');
--Queries--
--Query 1--Show me the information in the database
SELECT *
FROM client;
SELECT *
FROM soccerball;
SELECT *
FROM purchase;
SELECT *
FROM employee;
SELECT *
FROM job;
--"Forgot" Quantity Attribute. Adding that--
ALTER TABLE purchase
ADD quantity NUMERIC;
UPDATE purchase
SET quantity = '12000'
WHERE clientid = '1';
UPDATE purchase
SET quantity = '2492'
WHERE clientid = '2';
UPDATE purchase
SET quantity = '94203'
WHERE clientid = '3';
UPDATE purchase
SET quantity = '4394'
WHERE clientid = '4';
UPDATE purchase
SET quantity = '0'
WHERE clientid = '5';
UPDATE purchase
SET quantity = '4832'
WHERE clientid = '6';
UPDATE purchase
SET quantity = '10002'
WHERE clientid = '7';
SELECT *
FROM purchase;
--Queries Continued--
--Query 2--I want to know how many clients we have
SELECT Count(*)
FROM client;
--Query 3--Which client ordered the most soccer balls?***********
SELECT Max(quantity),
clientname
FROM purchase P,
client C
WHERE P.clientid = C.clientid
GROUP BY clientname
--Query 4--How many projects does each employe have?***********
SELECT Count(*)
FROM job
--Query 5--First purchases, first served. Show me the order of the purchases by date***********
SELECT clientname,
purchasedate
FROM purchase P,
client C
WHERE P.clientid = C.clientid
ORDER BY purchasedate;
--Query 6--Show me what kind of balls were purchased***********
SELECT B.ballid,
B.ballsize,
B.color,
B.material
FROM soccerball B,
purchase P,
client C
WHERE P.clientid = C.clientid
AND P.ballid = B.ballid
AND C.clientid = 1;
--Query 7--Show me who purchased what balls**************
SELECT B.ballid,
B.ballsize,
B.color,
B.material,
C.clientid,
clientname
FROM soccerball B,
purchase P,
client C
WHERE P.clientid = C.clientid
AND P.ballid = B.ballid
GROUP BY B.ballid,
B.ballsize,
B.color,
B.material,
C.clientid,
clientname'

Related

How to list total number of scholarships per department in SQL

I have 2 tables that look like this where I want to query how many scholarships (from Tuition table) each department (from Student table) has distributed:
I am thinking a join is necessary but am not sure how to do so.
Create tables
create table students (
sid int auto_increment primary key,
name varchar(100),
email varchar(100),
department varchar(100)
);
create table tutions (
id int auto_increment primary key,
sid int,
cost int,
scholarships int,
duedate timestamp default current_timestamp
);
Sample data
insert into students (name, email, department)
values
('John Doe', 'john#abc.xyz', 'B'),
('Jane Doe', 'jane#abc.xyz', 'A'),
('Jack Doe', 'jack#abc.xyz', 'C'),
('Jill Doe', 'jill#abc.xyz', 'B');
insert into tutions (sid, cost, scholarships)
values
(1, 1000, 2),
(2, 1000, 1),
(3, 1000, 7),
(4, 1000, 2);
Query (department-wise total scholarships)
SELECT department, sum(scholarships) as scholarships
FROM students s
JOIN tutions t ON s.sid = t.sid
GROUP BY department
Output
Running SQL Fiddle
Not sure It's something you want? And not sure scholarships is a number or name of scholarship? So I doubt it's a name as varchar string type.
### dummy record
CREATE TABLE students (
psu_id INTEGER PRIMARY KEY,
firstname VARCHAR NOT NULL,
lastname VARCHAR NOT NULL,
email VARCHAR NOT NULL,
department VARCHAR NOT NULL
);
CREATE TABLE tuition (
tuition_id INTEGER PRIMARY KEY,
student_id INTEGER NOT NULL,
semeter_cost INTEGER NOT NULL,
scholarships VARCHAR NOT NULL,
due_date DATE NOT NULL
);
INSERT INTO students VALUES (1, 'John', 'Hello', 'Jonh#email.com', 'Engineering');
INSERT INTO students VALUES (2, 'Bella', 'Fuzz', 'Bella#email.com', 'Computer');
INSERT INTO students VALUES (3, 'Sunny', 'World', 'Sunny#email.com', 'Science');
INSERT INTO tuition VALUES (1, 1, 4000, 'first_class_en', '2022-05-09' );
INSERT INTO tuition VALUES (2, 2, 3000, 'nobel', '2022-05-09' );
INSERT INTO tuition VALUES (3, 3, 5000, 'hackathon', '2022-05-09' );
INSERT INTO tuition VALUES (4, 1, 4500, 'second_class_en', '2022-05-09' );
-----------------
### query
SELECT s.department, count(t.scholarships)
FROM students s
JOIN tuition t
ON s.psu_id = t.student_id
GROUP BY s.department
### output
department, total_scholarships
Computer|1
Engineering|2
Science|1

SQL to assign covid patients to hospitals

I have 2 tables:
CREATE TABLE remdesivir_inventory
(
hospital_id int,
stock int,
state varchar(2)
);
CREATE TABLE remdesivir_requests
(
patient_id int,
prescribed_qty int,
state varchar(2)
);
I want to write a SQL that inserts rows in the remdesivir_assignments table
Every patient whose request can be fulfilled (until the stock runs out) will have a representative row in
the remdesivir_assignments table.
Each patient can be assigned to only 1 hospital (ie. requests cannot be split)
The 'state' of the patient and the hospital must match
CREATE TABLE remdesivir_assignments
(
patient_id int,
hospital_id int
);
Example:
INSERT INTO remdesivir_inventory VALUES (1, 200, 'CA');
INSERT INTO remdesivir_inventory VALUES (2, 100, 'FL');
INSERT INTO remdesivir_inventory VALUES (3, 500, 'TX');
INSERT INTO remdesivir_requests VALUES (10, 100, 'CA');
INSERT INTO remdesivir_requests VALUES (20, 200, 'FL');
INSERT INTO remdesivir_requests VALUES (30, 300, 'TX');
INSERT INTO remdesivir_requests VALUES (40, 100, 'AL');
INSERT INTO remdesivir_requests VALUES (50, 200, 'CA');
In this scenario, the following rows will be inserted to the remdesivir_assignments table
(10, 1)
(30, 3)
You can use a cumulative sum and join:
select rr.*, ri.hospital_id
from (select rr.*,
sum(prescribed_qty) over (partition by state order by patient_id) as running_pq
from remdesivir_requests rr
) rr join
remdesivir_inventory ri
on ri.state = rr.state and
rr.running_pq <= ri.stock
Here is a db<>fiddle.

Display User That Is Does Not Exist in Other Table

I have query that I am supposed to display The number of patients a physician can take on. He can have no more than 5 patients at a time. I have this query working with the following:
select PHYSICIAN.PHYSICIAN_ID,PHYSICIAN.firstname_physician,PHYSICIAN.lastname_physician, phone.phone_number, 5-count(patient.patient_id) as "Numbers of new patients he/she can take"
from patient, physician, physician_phone, phone
where physician.physician_id = patient.physician_id and PHYSICIAN_PHONE.PHYSICIAN_ID = PHYSICIAN.PHYSICIAN_ID and phone.PHONE_ID = physician_phone.PHONE_ID
group by PHYSICIAN.PHYSICIAN_ID, PHYSICIAN.firstname_physician, PHYSICIAN.lastname_physician, physician_phone.phone_id, phone.phone_number
having count(patient.patient_id)<5;
However this only displays the physicians that have patients not the physicians who have 0 patients connected to them.
My attempt to display the physicians who also have 0 patients was the following:
select PHYSICIAN.PHYSICIAN_ID,PHYSICIAN.firstname_physician,PHYSICIAN.lastname_physician, phone.phone_number, 5-count(patient.patient_id) as "Numbers of new patients he/she can take"
from patient, physician, physician_phone, phone
where physician.physician_id = patient.physician_id and PHYSICIAN_PHONE.PHYSICIAN_ID = PHYSICIAN.PHYSICIAN_ID and phone.PHONE_ID = physician_phone.PHONE_ID
group by PHYSICIAN.PHYSICIAN_ID, PHYSICIAN.firstname_physician, PHYSICIAN.lastname_physician, physician_phone.phone_id, phone.phone_number
having count(patient.physician_id)<5 OR NOT EXISTS ( Select patient.physician_id from patient Where patient.physician_id != physician.physician_Id group by patient.physician_id)
Below are the table creates to help anyone better understand the relationship between the tables
Create Table Physician (
Physician_ID integer not null,
Firstname_physician Char(30Char) not null,
lastname_physician Char(30Char) not null,
Constraint Physician Primary Key (Physician_ID));
Create Table Patient (
Patient_ID integer not null,
Patient_FirstName Char(20Char) not null,
Patient_LastName Char(20Char) not null,
Patient_MI Char(1Char) not null,
Patient_Gender Char(15Char) not null,
Staff_id integer not null,
Physician_ID integer not null,
Constraint Patient_pk Primary Key (Patient_ID),
Constraint HomeCareStaff_fk Foreign Key (Staff_ID) References HomeCareStaff(Staff_id),
Constraint Physician_ID_fk10 Foreign Key (Physician_ID) References Physician(Physician_ID));
Both tables queries return the same exact thing. Please see image results of query
Hope this makes sense Here are also the inserts
--populating Physician table--
insert into Physician values (100, 'Sasia', 'Applebottom');
insert into Physician values (101, 'Mac', 'Cheese');
insert into Physician values (102, 'Mick', 'Donalds');
insert into Physician values (103, 'Saint', 'West');
insert into Physician values (104, 'Chicago', 'West');
insert into Physician values (105, 'Mason', 'Disic');
---Populate Patient Table
insert into Patient values (150, 'Hayley', 'Beachump', 'F', 'Female', 50, 100);
insert into Patient values (151, 'Jacob', 'Stutzmen', 'K', 'Male', 51, 100);
insert into Patient values (152, 'Christina', 'Smush', 'P', 'Female', 52, 100);
insert into Patient values (153, 'Doris', 'Dorphish', 'D', 'Female', 53,100);
insert into Patient values (154, 'Adam', 'Wang', 'M', 'Male', 54, 100);
insert into Patient values (155, 'Levina', 'Reinhart', 'U', 'Female', 55, 101);
insert into Patient values (156, 'Harper', 'Mosbey', 'M', 'Male', 56, 102);
You can use this
select PHYSICIAN.PHYSICIAN_ID, PHYSICIAN.firstname_physician, PHYSICIAN.lastname_physician, phone.phone_number, count(patient.patient_id) as "Numbers of new patients he/she can take"
from patient, physician, physician_phone, phone
where physician.physician_id = patient.physician_id and PHYSICIAN_PHONE.PHYSICIAN_ID = PHYSICIAN.PHYSICIAN_ID and phone.PHONE_ID = physician_phone.PHONE_ID
group by PHYSICIAN.PHYSICIAN_ID, PHYSICIAN.firstname_physician, PHYSICIAN.lastname_physician, physician_phone.phone_id, phone.phone_number
having count(patient.patient_id) = 0;

postgresql outer join query to get all data from one table

I have two tables
CREATE TABLE REFERENCE_VALUES
(
REFERENCE_ID SERIAL,
REFERENCE_OBJ_NAME TEXT,
REFERENCE_VALUE_CODE BIGINT,
DISPLAY_NAME TEXT,
CREATED_ON TIMESTAMP,
MODIFIED_ON TIMESTAMP
);
ALTER TABLE REFERENCE_VALUES
ADD PRIMARY KEY (ID);
ALTER TABLE REFERENCE_VALUES
ADD FOREIGN KEY (REFERENCE_VALUE_CODE)
REFERENCES CATEGORY(ID);
CREATE TABLE CATEGORY
(
ID BIGSERIAL NOT NULL,
CODE TEXT NOT NULL,
NAME TEXT NOT NULL,
PARENT_ID BIGINT,
PATH TEXT,
COMP_ID BIGINT,
CREATED_ON TIMESTAMP,
MODIFIED_ON TIMESTAMP,
);
ALTER TABLE CATEGORY
ADD PRIMARY KEY (ID);
ALTER TABLE CATEGORY
ADD FOREIGN KEY (COMP_ID)
REFERENCES COMPANY_ID(ID);
I have the display names as DISPLAY_NAME in REFERENCE_VALUES table I want to SELECT all values from table CATEGORY but the value of NAME (In CATEGORY table) replaced by value from DISPLAY_NAME in REFERENCE_VALUES and if the value of of DISPLAY_NAME is NULL OR EMPTY i would keep the value of NAME (CATEGORY table).
I have been able to do that with the query below
SELECT C.ID, C.CODE, COALESCE(R.DISPLAY_NAME, C.NAME) as NAME, C.PARENT_ID, C.PATH, C.COMP_ID, C.CREATED_ON, C.MODIFIED_ON
FROM CATEGORY C
LEFT JOIN REFERENCE_VALUES R
ON C.ID = R.REFERENCE_VALUE_CODE
WHERE R.REFERENCE_OBJ_NAME = 'CATEGORY';
but i am getting only two records. How can i get all the records from the category table?
sample data to populate the tables
INSERT INTO CATEGORY VALUES (1, 'CVB', 'COMM VEH', NULL, 'CVB', 1, '2016-05-13 15:50:19.985', NULL);
INSERT INTO CATEGORY VALUES (2, 'LVB', 'AUTO', NULL, 'LVB', 1, '2016-05-13 15:50:19.994', NULL);
INSERT INTO CATEGORY VALUES (3, 'INB', 'INF', NULL, 'INB', 1, '2016-05-13 15:50:19.997', NULL);
INSERT INTO CATEGORY VALUES (4, 'OHB', 'OFF', NULL, 'OHB', 1, '2016-05-13 15:50:20', NULL);
INSERT INTO CATEGORY VALUES (5, 'LUB', 'LUB', NULL, 'LUB', 1, '2016-05-13 15:50:20.002', NULL);
INSERT INTO CATEGORY VALUES (52, 'TRA', 'TIE', 32, 'CVB.HA.TRA', 1, '2016-05-13 15:51:32.605', NULL);
INSERT INTO CATEGORY VALUES (68, 'PF', 'PER', 42, 'LVB.LA.PF', 1, '2016-05-13 15:51:33.117', NULL);
INSERT INTO CATEGORY VALUES (73, 'CE', 'CAR', 32, 'CVB.HA.CE', 1, '2016-05-13 15:51:33.733', NULL);
INSERT INTO CATEGORY VALUES (74, 'KP', 'KP', 32, 'CVB.HA.KP', 1, '2016-05-13 15:51:33.958', NULL);
INSERT INTO CATEGORY VALUES (26, 'RP', 'RING', 11, 'OHB.OH.RP', 1, '2016-05-13 15:51:30.149', NULL);
INSERT INTO CATEGORY VALUES (47, 'CP', 'COMP', 9, 'CVB.CV.CP', 1, '2016-05-13 15:51:31.903', NULL);
INSERT INTO CATEGORY VALUES (48, 'TB', 'TUB', 9, 'CVB.CV.TB', 1, '2016-05-13 15:51:31.905', NULL);
INSERT INTO CATEGORY VALUES (18, 'FB', 'FILT', 11, 'OHB.OH.FB', 1, '2016-05-13 15:51:30.002', NULL);
INSERT INTO REFERENCE_VALUES (ID, REFERENCE_OBJ_NAME, REFERENCE_VALUE_CODE, DISPLAY_NAME) VALUES (1, 'CATEGORY', 6, INDU CHANGED);
INSERT INTO REFERENCE_VALUES (ID, REFERENCE_OBJ_NAME, REFERENCE_VALUE_CODE) VALUES (2, 'CATEGORY', 7);
The WHERE condition filters out rows where R.REFERENCE_OBJ_NAME is null, which is all rows for which there are no matching REFERENCE_VALUE.
Maybe what you are trying to do is only join REFERENCE_VALUES where REFERENCE_OBJ_NAME is 'CATEGORY'. If so you could do it like this:
SELECT C.ID, C.CODE, COALESCE(R.DISPLAY_NAME, C.NAME) as NAME, C.PARENT_ID, C.PATH, C.COMP_ID, C.CREATED_ON, C.MODIFIED_ON
FROM CATEGORY C
LEFT JOIN REFERENCE_VALUES R
ON R.REFERENCE_OBJ_NAME = 'CATEGORY' AND C.ID = R.REFERENCE_VALUE_CODE

joining three tables together using Inner Joins

Using Table aliases, list the first name, last name and start date of students enrolled on the java fundamentals module:
I am having some trouble when running the query below.
SELECT stu.StudFName, stu.StudLName, enrol.StartDate
From Student stu
INNER JOIN Enrolment enrol
ON stu.StudID = enrol.StudID
INNER JOIN Module mod
ON enrol.ModCode = mod.ModCode
WHERE mod.ModName = 'Java Fundamentals'
Structure:
CREATE TABLE Student
(StudID INTEGER PRIMARY KEY,
StudFName VARCHAR(10) NOT NULL,
StudLName VARCHAR(10) NOT NULL,
DoB DATE NOT NULL,
Sex CHAR(1) NOT NULL CHECK (Sex IN ('M', 'F')),
Email VARCHAR(30) UNIQUE);
CREATE TABLE Staff
(StaffID INTEGER PRIMARY KEY,
Title VARCHAR(4) CHECK (Title IN ('Prof', 'Dr', 'Mr', 'Mrs', 'Miss')),
StaffFName VARCHAR(10) NOT NULL,
StaffLName VARCHAR(10) NOT NULL,
Email VARCHAR(30) UNIQUE,
Department VARCHAR(25) DEFAULT 'Not Assigned',
Extension INTEGER CHECK (Extension BETWEEN 0001 AND 9999));
CREATE TABLE Module
(ModCode CHAR(4) PRIMARY KEY,
ModName VARCHAR(25) NOT NULL,
ModCredits INTEGER NOT NULL CHECK (ModCredits IN (15, 30, 45, 60)),
ModLevel CHAR(3) NOT NULL CHECK (ModLevel IN ('UG1', 'UG2', 'UG3', 'MSc')),
ModLeader INTEGER NOT NULL,
Foreign Key (ModLeader) REFERENCES Staff (StaffID));
CREATE TABLE Enrolment
(ModCode CHAR(4) NOT NULL,
StudID INTEGER NOT NULL,
StartDate DATE NOT NULL,
PRIMARY KEY (ModCode, StudID),
Foreign Key (StudID) REFERENCES Student (StudID),
Foreign Key (ModCode) REFERENCES Module (ModCode));
The answer is... there is no trouble with your query.
It works just fine.
Check here
INSERT INTO Student (StudID, StudFName, StudLName, DoB, Sex, Email) VALUES
(1, 'Jack', 'Black', TO_DATE('2015/01/01', 'yyyy/mm/dd'), 'M', 'jack#email.com');
INSERT INTO Student (StudID, StudFName, StudLName, DoB, Sex, Email) VALUES
(2, 'Andrew', 'Wiggin', TO_DATE('2015/01/01', 'yyyy/mm/dd'), 'M', 'andrew#email.com');
INSERT INTO Student (StudID, StudFName, StudLName, DoB, Sex, Email) VALUES
(3, 'Bob', 'Marley', TO_DATE('2015/01/01', 'yyyy/mm/dd'), 'M', 'bob#email.com');
INSERT INTO Staff (StaffID, Title, StaffFName, StaffLName, Email, Extension) VALUES
(1, 'Prof', 'Joe', 'Smith', 'stuff#emal.com', 0001);
INSERT INTO Module (ModCode, ModName, ModCredits, ModLevel, ModLeader) VALUES
(1, 'Java Fundamentals', 30, 'UG1', 1);
INSERT INTO Module (ModCode, ModName, ModCredits, ModLevel, ModLeader) VALUES
(2, 'C# Fundamentals', 15, 'UG2', 1);
INSERT INTO Enrolment (ModCode, StudID, StartDate) VALUES
(1, 1, TO_DATE('2015/01/01', 'yyyy/mm/dd'));
INSERT INTO Enrolment (ModCode, StudID, StartDate) VALUES
(1, 2, TO_DATE('2015/01/02', 'yyyy/mm/dd'));
INSERT INTO Enrolment (ModCode, StudID, StartDate) VALUES
(2, 3, TO_DATE('2015/01/03', 'yyyy/mm/dd'));
-------------------------------------------------------------
SELECT stu.StudFName, stu.StudLName, enrol.StartDate
From Student stu
INNER JOIN Enrolment enrol ON stu.StudID = enrol.StudID
INNER JOIN Module mod ON enrol.ModCode = mod.ModCode
WHERE mod.ModName = 'Java Fundamentals'
Result
STUDFNAME STUDLNAME STARTDATE
----------------------------------------
Jack Black January, 01 2015
Andrew Wiggin January, 02 2015