Ex5:
a. The question asks the department name and number of employees. Since those are in
different tables, after FROM we will use 2 table names(it can be used with JOIN also) which are
Employee and Department, where NumberOfEmployees and Department Name come
respectively:
SELECT Dname, COUNT(*) AS Number_of_employees
FROM Employee, Department
In order to join tables correctly there should be the condition of appropriate columns which
are Department number:
WHERE Dno=Dnumber
For COUNT(*), GROUP BY is used with Dname and for selecting only more than 30000 HAVING
is used. So the result will be:
SELECT Dname, COUNT(*) AS Number_of_employees
FROM Employee, Department
WHERE Dno=Dnumber
GROUP BY Dname
HAVING AVG(Salary) > 30000
b. The query will be the same as 7.5.a) with 1 addition. In WHERE part another condition will
be used in order to extract female employees during JOIN process:
SELECT Dname, COUNT(*) AS Number_of_employees
FROM Employee, Department
WHERE Dno=Dnumber AND Sex='M'
GROUP BY Dname
HAVING AVG(Salary) > 30000
Ex6:
a. We need to find students who have straight As and their majors.
The following query will accomplish this
SELECT student.name,student.major
FROM student
INNER JOIN grade_report
ON student.student_number = grade_report.student_number
GROUP BY student.student_number, student.name
HAVING SUM(CASE WHEN grade_report.grade <> 'A' THEN 1 ELSE 0 END) = 0;
• Here we will join the tables 'student' and 'grade' so that we get a table where we have
students and their grades.
• We will also group the students by their names and their numbers.
• Lastly we count all of their grades that are not As. If there are any we will not display
the student.
• In this example, the output is blank, as there are no straight-A students.
• b. Now we need to find all of the students who do not have any As in any of their
courses
We can do this with the query
SELECT student.name,student.major
FROM student
INNER JOIN grade_report
ON student.student_number = grade_report.student_number
GROUP BY student.student_number, student.name
HAVING SUM(CASE WHEN grade_report.grade = 'A' THEN 1 ELSE 0 END) = 0;
• We are doing the same thing we did in the example a) but this time we are counting
how many As each of the students has.
• If the number of As is 0 we will print the students name and their major.
The output is
Ex7:
a.
SELECT Fname, Minit, Lname FROM EMPLOYEE WHERE Dno =
( SELECT Dno FROM EMPLOYEE WHERE Salary = ( SELECT MAX(Salary) FROM EMPLOYEE));
b.
SELECT Fname, Minit, Lname FROM EMPLOYEE WHERE Super_ssn =
( SELECT Ssn FROM EMPLOYEE WHERE Super_ssn = '888665555');
c.
SELECT Fname, Minit, Lname FROM EMPLOYEE WHERE Salary - 10000 >=
( SELECT MIN(Salary) FROM EMPLOYEE);