This document provides strategies for writing complex SQL queries using inner joins across multiple tables. It outlines a 3-step process: (1) identify the relevant columns in each table, (2) plot the join pathway between tables using primary and foreign keys, and (3) write expressions to select, filter, and order the columns as needed. Two examples are provided, with the first listing employee information and ordering by supervisor name, and the second aggregating hours by designer, project, and client.
2. 2 Strategy for Complex Joins (A) Identify which table columns contain the data needed. (B) Use the PK-FK pairs that make each join to plot the join “pathway”. Identify expressions to perform column and/or row operations needed and the clauses in which they belong.
3. 3 Table Columns (32) List the last names of all current employees, their position titles, the last names of their supervisors and the departments in which they work. The view should have 4 columns named “Supervisee”, “Position”, “Supervisor”, and “Department” and be in alphabetical order by supervisor’s last name. Person.lName Position.posTitle Person.lName Dept.deptName
4. 4 Join Pathway EmpRec empID Person.pID Dept.deptID supID deptID posID Position.posID Because Person.pID makes 2 joins to EmpRec, we’ll have to make a virtual copy of Person.
5. 5 Expressions (32) List the last names of all current employees, their position titles, the last names of their supervisors and the departments in which they work. The view should have 4 columns named “Supervisee”, “Position”, “Supervisor”, and “Department” and be in alphabetical order by supervisor’s last name. WHERE EmpRec.endDate IS NULL SELECT Person.lName AS Supervisee, Position.posTitle AS Position, Person.lName AS Supervisor, Dept.deptName AS Department ORDER BY Person.lName [Supervisor]
6. 6 SQL Statement Combine the 3 steps and tweak the syntax to get the complete query. SELECT P.lName AS Supervisee, A.posTitle AS Position, B.LName AS Supervisor, D.deptName AS Department FROM Person P, Position A, Person B, Dept D, EmpRec E WHERE P.pID=E.empID AND B.pID=E.supID AND E.deptID=D.deptID AND E.posID=A.posID AND E.endDate IS NULL ORDER BY B.lName;
7. 7 Another Example (33) List the designers’ and design assistants’ last names, the total numbers of hours each worked on each project, the project numbers, and the clients’ last names. The view should have 6 columns: “Designer”, “Design Assistant”, “Designer Hours”, “Design Assistant Hours”, “Project Number” and “Client”.
8. 8 Another Example SELECT A.lName AS Designer, B.lName AS [Design Assistant], SUM(H.desHr) AS [Designer Hours], SUM(H.desAstHr) AS [Design Assistant Hours], D.projNo AS [Project Number], C.lName AS Client FROM ProjDetail D, ProjHr H, Project P, Person A, Person B, Person C WHERE D.dtID=H.dtID AND P.projNo=D.projNo AND P.dID=A.pID AND P.daID=B.pID AND P.cID=C.pID GROUP BY D.projNo, A.lName, B.lName, C.lName;