Solution of 7

advertisement
Solution of 7.18 in SQL
Note: In the SQL, it is possible to specify the same query in multiple ways. We give one
possible solution for each query. For employee names, we sometimes include the MINIT
but do not show that in the result.
(a) Retrieve the names of employees in department 5 who work more than 10 hours per
week on the 'ProductX' project.
Result
FNAME
John
Joyce
LNAME
Smith
English
SELECT FNAME,MINIT,LNAME
FROM EMPLOYEE E, PROJECT P, WORKS_ON W
WHERE E.SSN=W.ESSN
AND
W.PNO=P.PNUMBER
AND
DNO=5
AND
HOURS >10
AND
PNAME='ProductX';
(b) List the names of employees who have a dependent with the same first name as
themselves.
Result (empty)
FNAME
LNAME
SELECT FNAME,MINIT,LNAME
FROM EMPLOYEE E, DEPENDENT D
WHERE E.SSN=D.ESSN
AND E. FNAME=D.DEPENDENT_NAME;
(c) Find the names of employees that are directly supervised by 'Franklin Wong'
Result
FNAME
John
Ramesh
Joyce
LNAME
Smith
Narayan
English
SELECT E.FNAME,E.MINIT,E.LNAME
FROM EMPLOYEE E, EMPLOYEE S
WHERE E.SUPERSSN=S.SSN
AND
S.FNAME='Franklin'
AND
S.LNAME='Wong';
(d) For each project, list the project name and the total hours per week (by all employees)
spent on that project.
Result
PNAME
ProductX
ProductY
ProductZ
Computerization
Reorganization
NewBenefits
TOT_HRS
52.5
37.5
50.0
55.0
25.0
55.0
SELECT P.PNAME,SUM(HOURS)
FROM PROJECT P, WORKS_ON W
WHERE P.PNUMBER=W.PNO
GROUP BY P.PNAME;
(e) Retrieve the names of employees who work on every project.
SELECT FNAME,MINIT,LNAME
FROM EMPLOYEE
WHERE NOT EXISTS
(
(SELECT PNUMBER
FROM PROJECT)
MINUS
(SELECT PNO
FROM WORKS_ON
WHERE SSN=ESSN)
);
Result (empty)
FNAME
LNAME
(f) Retrieve the names of employees who do not work on any project.
Result (empty)
FNAME
LNAME
SELECT FNAME,MINIT,LNAME
FROM EMPLOYEE
WHERE NOT EXISTS
(SELECT PNO
FROM WORKS_ON
WHERE SSN=ESSN
);
(g) For each department, retrieve the department name, and the average salary of
employees working in that department.
Result
DNUMBER
Research
Administration
Headquarters
AVG_SAL
33250
31000
55000
SELECT DNAME,AVG(SALARY)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER
GROUP BY DNAME;
(h) Retrieve the average salary of all female employees.
Result
AVG_F_SAL
31000
SELECT AVG(SALARY)
FROM EMPLOYEE
WHERE SEX='F';
(i) Find the names and addresses of employees who work on at least one project located
in Houston but whose department has no location in Houston.
Result
FNAME
Jennifer
LNAME
Wallace
ADDRESS
291 Berry, Bellaire, TX
SELECT FNAME,MINIT,LNAME,ADDRESS
FROM EMPLOYEE E, WORKS_ON W
WHERE E.SSN=W.ESSN
AND W.PNO IN (SELECT PNUMBER FROM PROJECT WHERE
PLOCATION='Houston')
MINUS
SELECT FNAME,MINIT,LNAME,ADDRESS
FROM EMPLOYEE E
WHERE DNO NOT IN (SELECT DNUMBER FROM DEPT_LOCATIONS WHERE
DLOCATION<> 'Houston')
(j) List the last names of department managers who have no dependents.
Result
LNAME
Borg
SELECT LNAME
FROM EMPLOYEE E, DEPARTMENT D
WHERE E.SSN=D.MGRSSN
AND NOT EXISTS (SELECT * FROM DEPENDENT WHERE MGRSSN=ESSN);
Download