Integrated Case Study
1. Consider a Hospital Database Schema below and perform the below
task:
a. create all the tables as per the ERD
b. Insert data into each of the table using Hospital.sql
Write all the queries using SQL *PLUS commands
1. Obtain the names of all physicians that have performed a medical
procedure they have never been certified to perform.
SELECT name AS "Physician"
FROM physician
WHERE employeeid IN
( SELECT undergoes.physician
FROM undergoes
LEFT JOIN trained_In ON
undergoes.physician=trained_in.physician
AND undergoes.procedures=trained_in.treatment
WHERE treatment IS NULL );
2. Same as the previous query, but include the following information in the
results: Physician name, name of procedure, date when the procedure
was carried out, name of the patient the procedure was carried out on.
SELECT P.Name AS Physician, Pr.Name AS Procedures,
U.DateUndergoes, Pt.Name AS Patient
FROM Physician P, Undergoes U, Patient Pt, Procedures Pr
WHERE U.Patient = Pt.SSN
AND U.Procedures = Pr.Code
AND U.Physician = P.EmployeeID
AND NOT EXISTS
(
SELECT * FROM Trained_In T
WHERE T.Treatment = U.Procedures
AND T.Physician = U.Physician
);
3. Obtain the names of all physicians that have performed a medical
procedure that they are certified to perform, but such that the
procedure was done at a date (Undergoes.Date) after the physician's
certification expired (Trained_In.CertificationExpires).
SELECT P.Name FROM
Physician AS P,
Trained_In T,
Undergoes AS U
WHERE T.Physician=U.Physician
AND T.Treatment=U.Procedures
AND U.DateUndergoes>T.CertificationExpires
AND P.EmployeeID=U.Physician;
4. Same as the previous query, but include the following information in the
results: Physician name, name of procedure, date when the procedure
was carried out, name of the patient the procedure was carried out on,
and date when the certification expired.
SELECT P.Name AS Physician, Pr.Name AS Procedures,
U.DateUndergoes, Pt.Name AS Patient, T.CertificationExpires
FROM Physician P, Undergoes U, Patient Pt, Procedures Pr,
Trained_In T
WHERE U.Patient = Pt.SSN
AND U.Procedures = Pr.Code
AND U.Physician = P.EmployeeID
AND Pr.Code = T.Treatment
AND P.EmployeeID = T.Physician
AND U.DateUndergoes > T.CertificationExpires;
5. Obtain the information for appointments where a patient met with a
physician other than his/her primary care physician. Show the following
information: Patient name, physician name, nurse name (if any), start
and end time of appointment, examination room, and the name of the
patient's primary care physician.
SELECT Pt.Name AS Patient, Ph.Name AS Physician, N.Name AS
Nurse, A.Startt, A.Endd, A.ExaminationRoom, PhPCP.Name AS PCP
FROM Patient Pt, Physician Ph, Physician PhPCP, Appointment A
LEFT JOIN Nurse N ON A.PrepNurse = N.EmployeeID
WHERE A.Patient = Pt.SSN
AND A.Physician = Ph.EmployeeID
AND Pt.PCP = PhPCP.EmployeeID
AND A.Physician <> Pt.PCP;
6. The Patient field in Undergoes is redundant, since we can obtain it from
the Stay table. There are no constraints in force to prevent
inconsistencies between these two tables. More specifically, the
Undergoes table may include a row where the patient ID does not
match the one we would obtain from the Stay table through the
Undergoes.Stay foreign key. Select all rows from Undergoes that exhibit
this inconsistency.
SELECT * FROM Undergoes U
WHERE Patient not in(
SELECT Patient FROM Stay S
WHERE U.Stay = S.StayID
);
7. Obtain the names of all the nurses who have ever been on call for room
123.
SELECT N.Name FROM Nurse N
WHERE EmployeeID IN
(
SELECT OC.Nurse FROM On_Call OC, Room R
WHERE OC.BlockFloor = R.BlockFloor
AND OC.BlockCode = R.BlockCode
AND R.RoomNumber = 123
);
8. The hospital has several examination rooms where appointments take
place. Obtain the number of appointments that have taken place in each
examination room.
SELECT ExaminationRoom, COUNT(AppointmentID) AS Number
FROM Appointment
GROUP BY ExaminationRoom;
9. Obtain the names of all patients (also include, for each patient, the name
of the patient's primary care physician), such that all the below conditions
are true:
-- The patient has been prescribed some medication by his/her primary
care physician.
-- The patient has undergone a procedure with a cost larger than $5,000
-- The patient has had at least two appointments where the nurse who
prepped the appointment was a registered nurse.
-- The patient's primary care physician is not the head of any department.
SELECT Pt.Name, PhPCP.Name FROM Patient Pt, Physician PhPCP
WHERE Pt.PCP = PhPCP.EmployeeID
AND EXISTS
(
SELECT * FROM Prescribes Pr
WHERE Pr.Patient = Pt.SSN
AND Pr.Physician = Pt.PCP
)
AND EXISTS
(
SELECT * FROM Undergoes U, Procedures Pr
WHERE U.Procedures = Pr.Code
AND U.Patient = Pt.SSN
AND Pr.Cost > 5000
)
AND 2 <=
(
SELECT COUNT(A.AppointmentID) FROM Appointment A, Nurse
N
WHERE A.PrepNurse = N.EmployeeID
AND N.Registered = 1
)
AND NOT Pt.PCP IN
(
SELECT Head FROM Department
);
2. Create the below Sales History Schema in Teradata and perform
the below Operations
1. Create the tables as per the below ER-Diagram
CREATE OR REPLACE TABLE COSTS
(
PROD_ID NUMBER,
TIME_ID DATEtime,
PROMO_ID NUMBER,
CHANNEL_ID NUMBER,
UNIT_COST NUMBER(10,2),
UNIT_PRICE NUMBER(10,2)
);
CREATE OR REPLACE TABLE PRODUCTS
(
PROD_ID NUMBER(10,0),
PROD_NAME VARCHAR(200),
PROD_DESC VARCHAR(200),
PROD_SUBCATEGORY VARCHAR(200),
PROD_SUBCATEGORY_ID NUMBER(10,0),
PROD_SUBCATEGORY_DESC VARCHAR(200),
PROD_CATEGORY VARCHAR(200),
PROD_CATEGORY_ID NUMBER(10,0),
PROD_CATEGORY_DESC VARCHAR(200),
PROD_WEIGHT_CLASS VARCHAR(200),
PROD_UNIT_OF_MEASURE VARCHAR(200),
PROD_PACK_SIZE VARCHAR(200),
SUPPLIER_ID NUMBER(10,2),
PROD_STATUS VARCHAR(200),
PROD_LIST_PRICE NUMBER(10,2),
PROD_MIN_PRICE NUMBER(10,2),
PROD_TOTAL NUMBER(10,2),
PROD_TOTAL_ID NUMBER(10,2),
PROD_SRC_ID NUMBER(10,2),
PROD_EFF_FROM NUMBER(10,2),
PROD_EFF_TO NUMBER(10,2),
PROD_VALID NUMBER(10,2)
);
CREATE OR REPLACE TABLE CHANNELS
(
CAHNNEL_ID NUMBER(10,0),
CHANNEL_DESC VARCHAR(100),
CHANNEL_CLASS VARCHAR(100),
CHANNEL_TOTAL NUMBER(10,0),
CHANNEL_TOTAL_ID NUMBER(10,0)
);
CREATE OR REPLACE TABLE SALES
(
PROD_ID NUMBER(10,0),
CUST_ID NUMBER(20,0),
TIME_ID DATETIME,
CAHNNEL_ID NUMBER(10,0),
PROMO_ID NUMBER(10,0),
QUANTITY_SOLD NUMBER(10,0),
AMOUNT_SOLD NUMBER(10,0)
);
CREATE TABLE times (
time_id DATE NOT NULL,
day_name VARCHAR2(9) NOT NULL,
day_number_in_week NUMBER(1) NOT NULL,
day_number_in_month NUMBER(2) NOT NULL,
calendar_week_number NUMBER(2) NOT NULL,
fiscal_week_number NUMBER(2) NOT NULL,
week_ending_day DATE NOT NULL,
week_ending_day_id NUMBER NOT NULL,
calendar_month_number NUMBER(2) NOT NULL,
fiscal_month_number NUMBER(2) NOT NULL,
calendar_month_desc VARCHAR2(8) NOT NULL,
calendar_month_id NUMBER NOT NULL,
fiscal_month_desc VARCHAR2(8) NOT NULL,
fiscal_month_id NUMBER NOT NULL,
days_in_cal_month NUMBER NOT NULL,
days_in_fis_month NUMBER NOT NULL,
end_of_cal_month DATE NOT NULL,
end_of_fis_month DATE NOT NULL,
calendar_month_name VARCHAR2(9) NOT NULL,
fiscal_month_name VARCHAR2(9) NOT NULL,
calendar_quarter_desc CHAR(7) NOT NULL,
calendar_quarter_id NUMBER NOT NULL,
fiscal_quarter_desc CHAR(7) NOT NULL,
fiscal_quarter_id NUMBER NOT NULL,
days_in_cal_quarter NUMBER NOT NULL,
days_in_fis_quarter NUMBER NOT NULL,
end_of_cal_quarter DATE NOT NULL,
end_of_fis_quarter DATE NOT NULL,
calendar_quarter_number NUMBER(1) NOT NULL,
fiscal_quarter_number NUMBER(1) NOT NULL,
calendar_year NUMBER(4) NOT NULL,
calendar_year_id NUMBER NOT NULL,
fiscal_year NUMBER(4) NOT NULL,
fiscal_year_id NUMBER NOT NULL,
days_in_cal_year NUMBER NOT NULL,
days_in_fis_year NUMBER NOT NULL,
end_of_cal_year DATE NOT NULL,
end_of_fis_year DATE NOT NULL );
CREATE TABLE countries (
country_id NUMBER NOT NULL,
country_iso_code CHAR(2) NOT NULL,
country_name VARCHAR2(40) NOT NULL,
country_subregion VARCHAR2(30) NOT NULL,
country_subregion_id NUMBER NOT NULL,
country_region VARCHAR2(20) NOT NULL,
country_region_id NUMBER NOT NULL,
country_total VARCHAR2(11) NOT NULL,
country_total_id NUMBER NOT NULL,
country_name_hist VARCHAR2(40));
CREATE TABLE promotions (
promo_id NUMBER(6) NOT NULL,
promo_name VARCHAR2(30) NOT NULL,
promo_subcategory VARCHAR2(30) NOT NULL,
promo_subcategory_id NUMBER NOT NULL,
promo_category VARCHAR2(30) NOT NULL,
promo_category_id NUMBER NOT NULL,
promo_cost NUMBER(10,2) NOT NULL,
promo_begin_date DATE NOT NULL,
promo_end_date DATE NOT NULL,
promo_total VARCHAR2(15) NOT NULL,
promo_total_id NUMBER NOT NULL);
CREATE TABLE customers (
cust_id NUMBER NOT NULL,
cust_first_name VARCHAR2(20) NOT NULL,
cust_last_name VARCHAR2(40) NOT NULL,
cust_gender CHAR(1) NOT NULL,
cust_year_of_birth NUMBER(4) NOT NULL,
cust_marital_status VARCHAR2(20) ,
cust_street_address VARCHAR2(40) NOT NULL,
cust_postal_code VARCHAR2(10) NOT NULL,
cust_city VARCHAR2(30) NOT NULL,
cust_city_id NUMBER NOT NULL,
cust_state_province VARCHAR2(40) NOT NULL,
cust_state_province_id NUMBER NOT NULL,
country_id NUMBER NOT NULL,
cust_main_phone_number VARCHAR2(25) NOT NULL,
cust_income_level VARCHAR2(30) ,
cust_credit_limit NUMBER ,
cust_email VARCHAR2(50) ,
cust_total VARCHAR2(14) NOT NULL,
cust_total_id NUMBER NOT NULL,
cust_src_id NUMBER ,
cust_eff_from DATE ,
cust_eff_to DATE ,
cust_valid VARCHAR2(1) );
2. Insert data into the tales as per the data files provided
3.Build a Student Management System using Python, where the user
will be able to perform the below activities:
a. Add New Student
b. View Students
c. Search Student
d. Update Student
e. Delete Student
All the above operation will be done using a Student.csv file which
will hold the details of the students. Please note to use a valid
exception handling mechanism.
import csv
import os
import platform
student_fields = ['roll', 'name', 'age', 'email', 'phone']
student_database = 'students.csv'
def display_menu():
print("--------------------------------------")
print(" Welcome to Student Management System")
print("---------------------------------------")
print("Enter 1: Add New Student")
print("Enter 2: View Students")
print("Enter 3: Search Student")
print("Enter 4: Update Student")
print("Enter 5: Delete Student")
print("Enter 6: Quit")
def add_student():
print("-------------------------")
print("Add Student Information")
print("-------------------------")
global student_fields
global student_database
student_data = []
for field in student_fields:
value = input("Enter " + field + ": ")
student_data.append(value)
with open(student_database, "a", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows([student_data])
print("Data saved successfully")
input("Press any key to continue")
return
def view_students():
global student_fields
global student_database
print("--- Student Records ---")
with open(student_database, "r", encoding="utf-8") as f:
reader = csv.reader(f)
for x in student_fields:
print(x, end='\t |')
print("\n-----------------------------------------------------------------")
for row in reader:
for item in row:
print(item, end="\t |")
print("\n")
input("Press any key to continue")
def search_student():
global student_fields
global student_database
print("--- Search Student ---")
roll = input("Enter roll no. to search: ")
with open(student_database, "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
if len(row) > 0:
if roll == row[0]:
print("----- Student Found -----")
print("Roll: ", row[0])
print("Name: ", row[1])
print("Age: ", row[2])
print("Email: ", row[3])
print("Phone: ", row[4])
break
else:
print("Roll No. not found in our database")
input("Press any key to continue")
def update_student():
global student_fields
global student_database
print("--- Update Student ---")
roll = input("Enter roll no. to update: ")
index_student = None
updated_data = []
with open(student_database, "r", encoding="utf-8") as f:
reader = csv.reader(f)
counter = 0
for row in reader:
if len(row) > 0:
if roll == row[0]:
index_student = counter
print("Student Found: at index ",index_student)
student_data = []
for field in student_fields:
value = input("Enter " + field + ": ")
student_data.append(value)
updated_data.append(student_data)
else:
updated_data.append(row)
counter += 1
# Check if the record is found or not
if index_student is not None:
with open(student_database, "w", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(updated_data)
else:
print("Roll No. not found in our database")
input("Press any key to continue")
def delete_student():
global student_fields
global student_database
print("--- Delete Student ---")
roll = input("Enter roll no. to delete: ")
student_found = False
updated_data = []
with open(student_database, "r", encoding="utf-8") as f:
reader = csv.reader(f)
counter = 0
for row in reader:
if len(row) > 0:
if roll != row[0]:
updated_data.append(row)
counter += 1
else:
student_found = True
if student_found is True:
with open(student_database, "w", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(updated_data)
print("Roll no. ", roll, "deleted successfully")
else:
print("Roll No. not found in our database")
while True:
display_menu()
choice = input("Enter your choice: ")
if choice == '1':
add_student()
runagain()
elif choice == '2':
view_students()
elif choice == '3':
search_student()
elif choice == '4':
update_student()
elif choice == '5':
delete_student()
else:
print("INVALID ACTIVITIES")
print("*******************************")
print("------Thank you----------------")
print("******************************")
4. Use python scripts to create the below tables using the
JSON data
f. Bill_fact(Sno,bill_ref_id,store_ref_id,customer_ref_id,do
ctor_ref_id,num_drugs_bill,total_quantity_bill,mrp_bill,to
tal_spend_bill,return_value_bill,returned_quantity_bill,q
uantity_ethical,quantity_generic,quantity_surgical,quant
ity_ayurvedic,quantity_general,quantity_otc,quantity_ch
ronic,quantity_acute,quantity_h1,DateID,payment_ref_i
d)
g. Dim_customer(Sno,customer_ref_id,CustomerName,cu
stomer_ref_key,NIF,Address,City,Region,ZipCode,Pho
neNumber,Address E-mail,Row Effective Date,Row
Expiration Date,Current Row Indicator)
h. Dim_doctor(Sno,doctor_ref_id,DoctorName,DoctorKey,
NIF,Address,City,Region,ZipCode,PhoneNumber,Addre
ss E-mail,Row Effective Date,Row Expiration
Date,Current Row Indicator)
i. Dim_Payment_Method(Sno,payment_ref_id,payment_d
escription)
j. Dim_Store(Sno,store_ref_id,StoreName,Store_ref_key,
Address,City,Region,ZipCode,PhoneNumber,Row
Effective Date,Row Expiration Date,Current Row
Indicator)
5. Use snowflake to perform the below task:
a. Download the dataset from Kaggle link
Train.csv
b. Create a database named Integrated_Project
create database Integrated_Project;
c. Create a schema named Ecommerce
create schema Ecommerce;
d. Create a table called
Customer_Orders(ID,Warehouse_block,Mode_of_Shipment,Custome
r_care_calls,Customer_rating,Cost_of_the_Product,Prior_purchases,
Product_importance,Gender,Discount_offered,Weight_in_gms,Reac
hed.on.Time_Y.N)
create table
Integrated_Project.Ecommerce.Customer_Orders(
ID varchar(100),
Warehouse_block varchar(100),
Mode_of_Shipment varchar(100),
Customer_care_calls varchar(100),
Customer_rating varchar(100),
Cost_of_the_Product varchar(100),
Prior_purchases varchar(100),
Product_importance varchar(100),
Gender varchar(100),
Discount_offered varchar(100),
Weight_in_gms varchar(100),
Reached_on_Time_Y_N varchar(100));
e.Use table stage to load the data into the table .