Can I reference this table? - sql

I am trying to show amount paid for each tutor sorted by month and then by tutor id. I have the first part correct and can sort by month but cannot sort by tutor id because it is from a different table.
Here is the script for my tables:
create table match_history
(match_id number(3),
tutor_id number(3),
student_id number(4),
start_date date,
end_date date,
constraint pk_match_history primary key (match_id),
constraint fk1_match_history foreign key (tutor_id) references tutor(tutor_id),
constraint fk2_match_history foreign key (student_id) references student(student_id));
create table tutor_report
(match_id number(3),
month date,
hours number(3),
lessons number(3),
constraint pk_tutor_report primary key (match_id, month),
constraint fk1_tutor_report foreign key (match_id) references match_history(match_id));
insert into tutor values (100, '05-JAN-2017', 'Active');
insert into tutor values (101, '05-JAN-2017', 'Temp Stop');
insert into tutor values (102, '05-JAN-2017', 'Dropped');
insert into tutor values (103, '22-MAY-2017', 'Active');
insert into tutor values (104, '22-MAY-2017', 'Active');
insert into tutor values (105, '22-MAY-2017', 'Temp Stop');
insert into tutor values (106, '22-MAY-2017', 'Active');
insert into student values (3000, 2.3);
insert into student values (3001, 5.6);
insert into student values (3002, 1.3);
insert into student values (3003, 3.3);
insert into student values (3004, 2.7);
insert into student values (3005, 4.8);
insert into student values (3006, 7.8);
insert into student values (3007, 1.5);
insert into match_history values (1, 100, 3000, '10-JAN-2017', null);
insert into match_history values (2, 101, 3001, '15-JAN-2017', '15-MAY-2017');
insert into match_history values (3, 102, 3002, '10-FEB-2017', '01-MAR-2017');
insert into match_history values (4, 106, 3003, '28-MAY-2017', null);
insert into match_history values (5, 103, 3004, '01-JUN-2017', '15-JUN-2017');
insert into match_history values (6, 104, 3005, '01-JUN-2017', '28-JUN-2017');
insert into match_history values (7, 104, 3006, '01-JUN-2017', null);
insert into tutor_report values (1, '01-JUN-2017', 8, 4);
insert into tutor_report values (4, '01-JUN-2017', 8, 6);
insert into tutor_report values (5, '01-JUN-2017', 4, 4);
insert into tutor_report values (4, '01-JUL-2017', 10, 5);
insert into tutor_report values (1, '01-JUL-2017', 4, 2);
This is what I have so far:
Select (hours * 10) as amount paid from tutor_report group by month, tutor_id
however obviously I cannot just say tutor_id at the end.

You can join match_history to get the tutor_id.
But your statement and the query don't match. If you want to sort use ORDER BY.
SELECT tr.hours * 10 amount_paid
FROM tutor_report tr
INNER JOIN match_history mh
ON mh.match_id = tr.match_id
ORDER BY tr.month,
mh.tutor_id;
If you want to aggregate, hours needs to be argument to some aggregation function. Maybe you're after the sum of hours?
SELECT sum(tr.hours) * 10 amount_paid
FROM tutor_report tr
INNER JOIN match_history mh
ON mh.match_id = tr.match_id
GROUP BY tr.month,
mh.tutor_id;

If you are grouping based on columns on two tables,you need to join them on the matching Id and then use group by
Select (hours * 10) as amount paid
from tutor_report a
join match_history b on a. match_id = b.match_id
group by month, tutor_id

Related

While combining tables, how to make a column distinct when it has multiple entries?

I'm trying to display course numbers from table student_enrollment and student names from table students, based on a distinct last_name from table professors. For example, there is a professor named "Wilson" - I would like to only display the courses Wilson's teaching and the students that are enrolled in these classes.
What I have so far is the following, which displays the unique course numbers that each student is enrolled in but does not take into consideration of professors.last_name:
SELECT students.student_name, student_enrollment.course_no
FROM students, student_enrollment, teach
WHERE students.student_no=student_enrollment.student_no
AND student_enrollment.course_no=teach.course_no
GROUP BY student_name,student_enrollment.course_no
Please see the four queried tables (students, student_enrollment, teach, professors) below for more information:
create table students
(
student_no integer,
student_name varchar(20),
age integer
);
insert into students values (1, 'Harpreet', 19);
insert into students values (2, 'Doug', 18);
insert into students values (3, 'Abdul', 21);
insert into students values (4, 'Mohammad', 20);
insert into students values (5, 'Ralph', 19);
insert into students values (6, 'Prateek', 22);
insert into students values (7, 'Michael', 19);
insert into students values (8, 'Jack', 19);
insert into students values (9, 'Chin', 17);
insert into students values (10, '', 20);
create table courses
(
course_no varchar(5),
course_title varchar(20),
credits integer
);
insert into courses values ('CS110', 'Pre Calculus', 4);
insert into courses values ('CS180', 'Physics', 4);
insert into courses values ('CS107', 'Intro to Psychology', 3);
insert into courses values ('CS210', 'Art History', 3);
insert into courses values ('CS220', 'US History', 3);
create table student_enrollment
(
student_no integer,
course_no varchar(5)
);
insert into student_enrollment values (1, 'CS110');
insert into student_enrollment values (1, 'CS180');
insert into student_enrollment values (1, 'CS210');
insert into student_enrollment values (2, 'CS107');
insert into student_enrollment values (2, 'CS220');
insert into student_enrollment values (3, 'CS110');
insert into student_enrollment values (3, 'CS180');
insert into student_enrollment values (4, 'CS220');
insert into student_enrollment values (5, 'CS110');
insert into student_enrollment values (5, 'CS180');
insert into student_enrollment values (5, 'CS210');
insert into student_enrollment values (5, 'CS220');
insert into student_enrollment values (6, 'CS110');
insert into student_enrollment values (7, 'CS110');
insert into student_enrollment values (7, 'CS210');
create table professors
(
last_name varchar(20),
department varchar(12),
salary integer,
hire_date date
);
insert into professors values ('Chong', 'Science', 88000, '2006-04-18');
insert into professors values ('Brown', 'Math', 97000, '2002-08-22');
insert into professors values ('Jones', 'History', 67000, '2009-11-17');
insert into professors values ('Wilson', 'Astronomy', 110000, '2005-01-15');
insert into professors values ('Miller', 'Agriculture', 82000, '2008-05-08');
insert into professors values ('Williams', 'Law', 105000, '2001-06-05');
create table teach
(
last_name varchar(20),
course_no varchar(5)
);
insert into teach values ('Chong', 'CS180');
insert into teach values ('Brown', 'CS110');
insert into teach values ('Brown', 'CS180');
insert into teach values ('Jones', 'CS210');
insert into teach values ('Jones', 'CS220');
insert into teach values ('Wilson', 'CS110');
insert into teach values ('Wilson', 'CS180');
insert into teach values ('Williams', 'CS107');
Note that there may be multiple professors teaching the same course (and there are students enrolled in the same course more than once).
If anyone has a pointer as to what I am missing here, please let me know! I'm new to SQL and have tried a few ideas unsuccessfully.
A simple and quick way to organize the sql is to use sub clause.
select s.*, c.*
from student_enrollment se
inner join student s on se.student_no = s.student_no
inner join course c on se.course_no = c.course_no
where course_no in (select course_no from teach where last_name = 'Wilson')

Analytical Query in SQL for MIN, MAX, and AVG

I am trying to figure out a query for this question: for each major, list the number of students, minimum GPA, maximum GPA, average GPA, minimum age, maximum age, and average age. (Show GPA with 2 decimal points, age with no decimal points. You may find it useful to create a view with one of the previous queries for this one.)
This is the script to create the table for SQL!
REM drop all the tables. Note that you need to drop the
REM dependent table first before dropping the base tables.
drop table Reg;
drop table Student;
drop table Course;
REM Now create all the tables.
create table Student
(
sid char(10) primary key,
sname varchar(20) not null,
gpa float,
major char(10),
dob DATE
);
create table Course
(
cno char(10) primary key,
cname varchar(20) not null,
credits int,
dept char(10)
);
create table Reg
(
sid references Student(sid) on delete cascade,
cno references Course(cno) on delete cascade,
grade char(2),
primary key (sid, cno)
);
REM Now insert all the rows.
insert into Student values ('111', 'Joe', 3.5 , 'MIS', '01-AUG-2000');
insert into Student values ('222', 'Jack', 3.4 , 'MIS', '12-JAN-1999');
insert into Student values ('333', 'Jill', 3.2 , 'CS', '15-MAY-1998');
insert into Student values ('444', 'Mary', 3.7 , 'CS', '17-DEC-2001');
insert into Student values ('555', 'Peter', 3.8 , 'CS', '19-MAR-1999');
insert into Student values ('666', 'Pat', 3.9, 'Math', '31-MAY-2000');
insert into Student values ('777', 'Tracy', 4.0, 'Math', '18-JUL-1997');
insert into Course values ('c101', 'intro', 3 , 'CS');
insert into Course values ('m415', 'database', 4 , 'Bus');
insert into Course values ('m215', 'programming', 4 , 'Bus');
insert into Course values ('a444', 'calculus', 3 , 'Math');
insert into Reg values ('111', 'c101', 'A');
insert into Reg values ('111', 'm215', 'B');
insert into Reg values ('111', 'm415', 'A');
insert into Reg values ('222', 'm215', 'A');
insert into Reg values ('222', 'm415', 'B');
insert into Reg values ('333', 'c101', 'A');
insert into Reg values ('444', 'm215', 'C');
insert into Reg values ('444', 'm415', 'B');
insert into Reg values ('555', 'c101', 'B');
insert into Reg values ('555', 'm215', 'A');
insert into Reg values ('555', 'm415', 'A');
insert into Reg values ('666', 'c101', 'A');
This is what I have so far:
SELECT major,
count(distinct SID) as students,
round(min(gpa), 2),
round(max(gpa), 2),
round(avg(gpa), 2),
trunc(min(sysdate - dob)/365) as min_age,
trunc(max(sysdate - dob)/365) as max_age,
trunc(avg(sysdate - dob)/365) as avg_age,
FROM Student
GROUP BY MAJOR;
According to your input I've made a query that I belive will show you the results. (It was kind hard to read the tables the way you posted it). The syntax may differ according to your DBMS (SQL Server, MySQL, REdshift, Postgres, etc)
Here is the query:
SELECT major,
COUNT(*) as students,
ROUND(MIN(gpa), 2) as min_gpa,
ROUND(MAX(gpa), 2) as max_gpa,
ROUND(AVG(gpa), 2) as avg_gpa,
MIN(DATEDIFF(year, current_date, dob)) as min_age,
MAX(DATEDIFF(year, current_date, dob)) as max_age,
AVG(DATEDIFF(year, current_date, dob)) as avg_date
FROM students st left join Course co on co.dept = st.major
GROUP BY major
Your query is completely fine (just remove comma(,) after avg_age.
SELECT major,
count(distinct SID) as students,
round(min(gpa), 2) as MinGPA,
round(max(gpa), 2) as MaxGPA,
round(avg(gpa), 2) as AvgGPA,
round(min(sysdate - dob)/365,0) as min_age,
round(max(sysdate - dob)/365,0) as max_age,
round(avg(sysdate - dob)/365,0) as avg_age
FROM Student
GROUP BY MAJOR;
You can also use months_between() with floor() to get the same result:
select * from student;
SELECT major,
count(distinct SID) as students,
round(min(gpa), 2) as MinGPA,
round(max(gpa), 2) as MaxGPA,
round(avg(gpa), 2) as AvgGPA,
floor(min(months_between(trunc((sysdate)), dob)) /12) as min_age,
floor(max(months_between(trunc((sysdate)), dob)) /12) as max_age,
floor(avg(months_between(trunc((sysdate)), dob)) /12) as avg_age
FROM Student
GROUP BY MAJOR;

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.

One time each one

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

Running an SQL Script file and having issues printing the Current_Orders table cant understand the errors

I have to prepare and execute a script file to create and populate a relational database in Oracle with data about customers, current orders, and products. These are the relationships: Each customer can place any number of current orders and each current order is placed by one customer.Each current order is for one product but each product can be in any number of
current orders.
I can't figure out the errors when running this script. The Customer and Products table are successfully filled, but the Current_Orders table is not. There are a few error codes that appear when I run it but I am not understanding them as I am fairly new to SQL. Any help would be appreciated. Thanks! ORA-00001, ORA-00955, ORA-02449.
drop table Customer;
drop table Current_Orders;
drop table Products;
create table Customer
(Customer_Number integer not null,
Customer_Name char(20) not null,
Customer_City char(20) not null,
PRIMARY KEY(Customer_Number));
create table Products
(Product_Number integer not null,
Product_Description char(20) not null,
Unit_Price integer not null,
PRIMARY KEY (Product_Number));
create table Current_Orders
(Order_Number integer not null,
Order_Date date not null,
Shipping_Method char(20) not null,
Product_Number integer not null,
Quantity_Ordered integer not null,
Customer_Number integer not null,
PRIMARY KEY(Order_Number), FOREIGN KEY(Customer_Number)
references Customer(Customer_Number) ON DELETE CASCADE,
FOREIGN KEY(Product_Number) references Products(Product_Number)
ON DELETE CASCADE);
insert into Customer
values (1, 'Khizur Sheikh', 'Milpitas');
insert into Customer
values (2, 'Fatima Sheikh', 'Fremont');
insert into Customer
values (3, 'Syed Sheikh', 'Davis');
insert into Customer
values (4, 'Mohammed Sheikh', 'Oakland');
insert into Customer
values (5, 'Ali Sheikh', 'Dublin');
insert into Products
values (6, 'iphone', 300);
insert into Products
values (7, 'ipad', 400);
insert into Products
values (8, 'imac', 500);
insert into Products
values (9, 'ipod', 600);
insert into Products
values (10, 'ihome', 700);
insert into Products
values (11, 'apple', 800);
insert into Products
values (12, 'banana', 900);
insert into Products
values (13, 'orange', 1000);
insert into Products
values (14, 'grape', 1100);
insert into Products
values (15, 'avocado', 1200);
insert into Products
values (16, 'bread', 1300);
insert into Products
values (17, 'muffin', 1400);
insert into Products
values (18, 'cheese', 1500);
insert into Products
values (19, 'milk', 1600);
insert into Products
values (20, 'brownies', 1700);
insert into Products
values (21, 'candy', 1800);
insert into Products
values (22, 'soup', 1900);
insert into Products
values (23, 'strawberry', 11000);
insert into Products
values (24, 'cookies', 50);
insert into Products
values (25, 'chocolate', 10);
insert into Current_Orders
values (26, '22-oct-2017', 'truck', 6, 1, 1);
insert into Current_Orders
values (27, '22-nov-2017', 'ship', 7, 1, 2);
insert into Current_Orders
values (28, '22-dec-2017', 'train', 8, 3, 3);
insert into Current_Orders
values (29, '22-jan-2017', 'truck', 9, 2, 4);
insert into Current_Orders
values (30, '22-feb-2017', 'train', 10, 1, 5);
insert into Current_Orders
values (31, '22-mar-2017', 'truck', 12, 4, 2);
insert into Current_Orders
values (32, '22-apr-2017', 'plane', 17, 7, 4);
insert into Current_Orders
values (33, '22-may-2017', 'train', 19, 1, 5);
insert into Current_Orders
values (34, '22-jun-2017', 'ship', 22, 3, 2);
insert into Current_Orders
values (35, '22-jan-2017', 'ship', 21, 4, 3);
commit;
All the commands in your script work fine while running for the first time. However Issue seems to occur when you run the DROP TABLE statements on second and successive executions when table exists and has data.
drop table Customer;
drop table Current_Orders;
Error report - ORA-02449: unique/primary keys in table referenced by
foreign keys
02449. 00000 - "unique/primary keys in table referenced by foreign keys"
*Cause: An attempt was made to drop a table with unique or
primary keys referenced by foreign keys in another table.
*Action: Before performing the above operations the table, drop the
foreign key constraints in other tables.
I see you have defined a FOREIGN KEY on the column Customer_Number
FOREIGN KEY(Customer_Number)
references Customer(Customer_Number) ON DELETE CASCADE
So, when you try to DROP from Table Customer before Current_Orders , you are basically deleting parent record before deleting the child record which is not allowed. ORA-00955 and ORA-00001 occur as a consequence.
So, follow this order to drop tables in your script.
drop table Current_Orders;
drop table Products;
drop table Customer;