SQL: nested query with tuple constructor - sql

I have some difficulties dealing with an SQL exercise for my Intro to Database course. The SQL standard we mainly use is the Oracle one (the one compatible with Apex).
I have the following SQL database (primary keys bold):
TEENAGER(SSN, Name, Surname, BirthDate, CityOfResidence, Sex)
ACTIVITY(ActivityCode, AName, Description, Category)
SUMMER-CAMP(CampCode, CampName, City)
SUBSCRIPTION-TO-ACTIVITY-IN-SUMMER-CAMP(SSN,ActivityCode, CampCode,
SubscriptionDate)
This is what the exercise asks:
"For each teenager, born before 2005, who subscribed to activities
organized by at least 5 different summer camps, show name, surname,
birth date of the teenager and the name of each summer camp to which
the teenager subscribed to all the different activities organized by
the camp."
I do not have any problem finding the SSNs of the teenagers born before 2005 and who subscribed to at least 5 camps and I am able to find the number of different activities organized by the camp. How do I manage to use this information to find the final result?
Now, this is my attempt to a solution (I added two in-line comments with "#" for clarity):
FROM TEENAGER T, SUMMER-CAMP SC, SUBSCRIPTION-TO-ACTIVITY-IN-SUMMER-CAMP STAISC
WHERE T.SSN = STAISC.SSN AND STAISC.CampCode = SC.CampCode
AND SSN IN (SELECT T.SSN #born before 2005 and at least 5 camps
FROM TEENAGER T, SUBSCRIPTION-TO-ACTIVITY-IN-SUMMER-CAMP STAISC
WHERE T.BirthDate < TO_DATE('01/01/2005', 'DD/MM/YYYY')
AND T.SSN = STAISC.SSN
GROUP BY T.SSN
HAVING COUNT(DISTINCT STAISC.CampCode) > 4)
GROUP BY STAISC.CampCode, T.SSN
HAVING (STAISC.CampCode, COUNT(DISTINCT ActivityCode)) IN (SELECT CampCode, COUNT(DISTINCT ActivityCode) #number of activities in camps
FROM SUBSCRIPTION-TO-ACTIVITY-IN-SUMMER-CAMP
GROUP BY CampCode)```
As you can see, I am using a tuple constructor in the outer-most query in a HAVING clause to try and use the information about the total number of activities organised in a camp. Am I allowed to do that and would it work? (The professor did not give us any database since in the exam we will have to write down the query without being able to run it).
Thanks in advance!

I answer to my own question since I found a correct solution:
SELECT T.SSN, SC.CampCode, T.Name, T.Surname, T.BirthDate, SC.CampName
FROM TEENAGER T, SUMMER-CAMP SC, SUBSCRIPTION-TO-ACTIVITY-IN-SUMMER-CAMP STAISC
WHERE BirthDate < TO_DATE('01/01/2005', 'DD/MM/YYYY')
AND T.SSN = STAISC.SSN AND STAISC.CampCode = SC.CampCode
AND T.SSN IN(SELECT SSN FROM SUBSCRIPTION-TO-ACTIVITY-IN-SUMMER-CAMP
GROUP BY SSN
HAVING COUNT(DISTINCT CampCode))
GROUP BY T.SSN, SC.CampCode
HAVING COUNT(DISTINCT STAISC.ActivityCode) = (SELECT COUNT(ActivityCode)
FROM SUBSCRIPTION-TO-ACTIVITY-IN-SUMMER-CAMP STAISC2
WHERE STAISC.CampCode = STAISC2.CampCode)

Related

ORACLE Retrieving data from 4 tables

I have the following tables:
Students(id, name, surname)
Courses(course id)
Course_Signup(id, student_id, course_id, year)
Grades(signup_id, mark)
I want to display all the students(id, name, surname) with their final grade (where final grade = avg of the grades of all courses), but only for the students that have passed all the courses for which they have sign-up in the current year.
This is what I tried:
SELECT s."id", s."name", s."surname", AVG(g."mark") AS "finalGrade"
FROM "STUDENT" s,
"course sign-up" csn
join "GRADES" g
on csn."id" = g."signup_id"
WHERE csn."year" >= '01-01-2022'
HAVING "finalGrade" >= 5.00
GROUP BY s."id"
However, after adding the last 2 lines, regarding the finalGrade condition, I get an invalid identifier error. Why is that?
Uh, oh. Did you really create tables using lower letter case names enclosed into double quotes? If so, get rid of them (the sooner, the better) because they only cause problems.
Apart from that, uniformly use joins - in your from clause there's the student table which isn't joined to any other table and results in cross join.
Don't compare dates to strings; use date literal (as I did), or to_date function with appropriate format model.
As of error you got: you can't reference expression's alias ("finalGrade") as is in the having clause - use the whole expression.
Also, group by should contain all non-aggregated columns from the select column list.
This "fixes" error you got, but - I suggest you consider everything I said:
SELECT s."id", s."name", s."surname", AVG(g."mark") AS "finalGrade"
FROM "STUDENT" s,
"course sign-up" csn
join "GRADES" g
on csn."id" = g."signup_id"
WHERE csn."year" >= date '2022-01-01'
GROUP BY s."id", s."name", s."surname"
HAVING AVG(g."mark") >= 5.00

Oracle SQL Programming Query

Apologies, but I have little experience with SQL programming and I need to figure out why my SQL query isn't working...I have been trying to no avail to work this out!
Database SQL file located here
Database schema as follows:
DEPARTMENT(deptnum, descrip, instname, deptname, state, postcode)
ACADEMIC(acnum, deptnum*, famname, givename, initials, title)
PAPER(panum, title)
AUTHOR(panum*, acnum*)
FIELD(fieldnum, id, title)
INTEREST(fieldnum*, acnum*, descrip)
Essentially I am trying to find out the following, and having some real issues:
Need to find the academics that have more than 1 research interest. I need to list the acnum, famname and givename of these academics, sorted by famname and then by givename.
select A.acnum, A.givename, A.famname, INTEREST.FIELDNUM
from ACADEMIC A, INTEREST
where A.ACNUM = INTEREST.ACNUM
having count (Interest.acnum) > 1;
Something like this?
I need to find if there are any research fields where no academics have no interest in? I need to print the total number of research fields like this. I believe the query uses a SET operator.
I need to find the research fields that have the largest number of interested academics. I need to output the fieldnum and number of interested academics.
The schema is not quite clear to me, but here is a starting point:
1) First one:
SELECT a.acnum, a.famname ,a.givename, count(i.fieldnum)
FROM ACADEMIC a INNER JOIN INTEREST i ON a.acnum = i.acnum
GROUP BY a.acnum, a.famname ,a.givename
HAVING COUNT(i.fieldnum) > 1
ORDER BY a.famname ,a.givename;
2) If you just need the number of them:
SELECT COUNT(1)
FROM FIELD f
WHERE NOT EXISTS(SELECT 1
FROM ACADEMIC a
INNER JOIN INTEREST i ON a.acnum = i.acnum
WHERE f.fieldnum = i.fieldnum);
3) It's a bit fuzzy, because I don't know what largest actually means, but here is the sorted list:
SELECT f.fieldnum, count(a.acnum) as number_of_interested_academics
FROM FIELD f
INNER JOIN INTEREST i ON f.fieldnum = i.fieldnum
INNER JOIN ACADEMIC a ON i.acnum = a.acnum
GROUP BY f.fieldnum
ORDER BY count(a.acnum) DESC;

sql join and minus

I seem to be having problem getting a certain query to work. I know I'm so close. Here's a copy of my er diagram
I think I am so close to achieving what I want to do with this code, only I get invalid identifier when trying to run it. I think its because the practice is being changed somehow after joining, as I am only getting invalid identifier on row 5?
SELECT staffid, staff_firstname, staff_surname, practice.practice_name, practice.practice_city
from staff
join practice on staff.practiceid = practice.practiceid
MINUS
SELECT staffid, staff_firstname, staff_surname, practice.practice_name, practice.practice_city
from staff
where role = 'GP';
Basically I'm trying to use the minus construct to find practices which do not employ a GP and include some information such as the CITY and practice_address.
I can use the minus construct to find out how many staff do not have the role of GP like so:
SELECT staffid, staff_firstname, staff_surname
from staff
MINUS
SELECT staffid, staff_firstname, staff_surname
from staff
where role = 'GP';
where I get the results:
STAFFID STAFF_FIRS STAFF_SURN
__________ __________ __________
8 NYSSA THORNTON
9 MONA BRADSHAW
10 GLORIA PENA
I'm struggling to use the join with the minus construct to get information about the GP's practice address and city etc.
Any help would be greatly appreciated!
The second select, after the minus, is referring to columns from the practice table - but it doesn't join to it:
SELECT staffid, staff_firstname, staff_surname,
practice.practice_name, practice.practice_city
from staff
join practice on staff.practiceid = practice.practiceid
MINUS
SELECT staffid, staff_firstname, staff_surname,
practice.practice_name, practice.practice_city
from staff
join practice on staff.practiceid = practice.practiceid
where role = 'GP';
That isn't going to give you what you want though, it will just remove the rows for staff that are GPs, not all trace of practices that have any GPs - non-GP staff at all practices will still be shown.
if you don't want the remaining staff details you only need to include the columns from the practice table in the select lists, and the minus would then give you what you want (and Gordon Linoff has shown two alternatives to minus in that case). If you do want the remaining staff details then you can use a not-exists clause rather than a minus - something like:
select s.staffid, s.staff_firstname, s.staff_surname,
p.practice_name, p.practice_city
from staff s
join practice p on s.practiceid = p.practiceid
where not exists (
select 1
from staff s2
where s2.practice_id = p.practice_id
and s2.role = 'GP
);
This is similar to Gordon's second query but has an extra join to staff for the details. Again, if you don't want those, use Gordon's simpler query.
You could also use an aggregate check, or could probably do something with an analytic function if you've learned abput those, to save having to hit the tables twice.
Your original query only operates on the level of "staff", not "practice". I would be inclined to solve this using aggregation:
select p.practice_name, p.practice_city
from staff s join
practice p
on s.practiceid = p.practiceid
group by p.practice_name, p.practice_city
having sum(case when s.role = 'GP' then 1 else 0 end) = 0;
Or, even better:
select p.*
from practice p
where not exists (select 1
from staff s
where s.practiceid = p.practiceid and s.role = 'GP'
);
I think this is the simplest and most direct interpretation of your question.

Creating Report, repetition in report output, Ms Access SQL

SELECT NMC.*, Exam.Final_Exam_Level
FROM
(SELECT Technicians.Technician_ID AS Technician_ID,
Technicians.First_Name AS First_Name,
Technicians.Surname AS Surname,
MAX(New_Models.Date_Issued) AS Last_Course_Date,
MAX(New_Models.Issue) AS Last_Issue,
MAX(New_Models.Model_ID) AS Last_Model_ID,
Technicians.Course_Level AS No_Training_Courses
FROM New_Models, New_Models_Allocation, Technicians
WHERE New_Models.Model_ID=New_models_Allocation.Model_ID
And Technicians.Technician_ID=New_Models_Allocation.Technician_ID
GROUP BY Technicians.Technician_ID, Technicians.Course_Level, First_Name, Surname
ORDER BY MAX(New_Models.Model_ID) DESC)
AS NMC
INNER JOIN (SELECT Technicians.Technician_ID, COUNT(*) AS Final_Exam_Level
FROM Technicians, Exams, Exam_Allocation
WHERE (Technicians.Technician_ID)=Exam_Allocation.Technician_ID
And ((Exams.Exam_ID)=Exam_Allocation.Exam_ID)
And (Exams.Date_Taken)<=#12/31/2010#
GROUP BY Technicians.Technician_ID, Technicians.Course_Level
ORDER BY Technicians.Technician_ID)
AS Exam ON Exam.Technician_ID=NMC.Technician_ID;
This query shows each technician, Last Exam, Last New_Model, Last course.
SELECT Technicians.Technician_ID, Jobs.Job_ID, Jobs.Date_Occured, Fix
FROM Technicians, Jobs, Tech_Allocation, Recovery
WHERE Technicians.Technician_ID=Tech_Allocation.Technician_ID
And Jobs.Job_ID=Tech_Allocation.Job_ID
And Jobs.Job_ID=Recovery.Job_ID
And Jobs.Date_Occured>=#1/1/2010#
And Jobs.Date_Occured<=#12/31/2010#
ORDER BY Fix;
This query shows the jobs each technician has done.
However, when creating a report in Ms Access, the jobs are repeated. Hence, instead of a technician having done 3 jobs, it shows 12 for example. Although when running the second query itself, results aren't repeated.
Any Help?
For obvious reasons, I don't usually read other people's SQL queries, but your example was very well formatted. Is this the problem?
INNER JOIN (SELECT Technicians.Technician_ID, COUNT(*) AS Final_Exam_Level
...
GROUP BY Technicians.Technician_ID, Technicians.Course_Level
These 2 lines are from the 2nd subquery of your first query. You have 1 index field (Technician_ID), but 2 grouping fields (Technician_ID and Course_Level). This would produce results like:
Technician_ID Final_Exam_Level
Bob 5
Bob 4
Nadine 5
I recommend either removing Course_Level from the Group By or adding it to the Select row.

Trouble with oracle sql query

I am trying to make a query of
"What are the names of the producers
with at least 2 properties with areas
with less than 10"
I have made the following query that seems to work:
select Producers.name
from Producers
where (
select count(Properties.prop_id)
from Properties
where Properties.area < 10 and Properties.owner = Properties.nif
) >= 2;
yet, my lecturer was not very happy about it. He even thought (at least gave me the impression of) that this kind of queries wouldn't be valid in oracle.
How should one make this query, then? (I have at the moment no way of getting to speak with him btw).
Here are the tables:
Producer (nif (pk), name, ...)
Property (area, owner (fk to
producer), area, ... )
The having clause is typically used to filter on aggregate data (like counts, sums, max, etc).
select
producers.name,
count(*)
from
producers,
property
where
producers.nif = property.owner and
property.area < 10
group by
producers.name
having
count(*) >= 2
select P.name
from Producers p, Properties pr
where p.nif = pr.Owner
AND Properties.area < 10
GROUP BY Producers.name
having Count(*) >= 2