考虑以下示例数据:
Table: timeworked
employeeid fiscalmonth projectcode hoursworked
1 janfy13 101 16
2 janfy13 101 11
1 janfy13 102 8
Table: employees
[employee id] manager
1 Manager A
2 Manager B
Table: kronoscodes
projectcode projectname
101 Project 101
102 Project 102
103 Project 103
使用直接的 INNER JOINS,您的“经理报告”的略微简化版本将如下所示:
SQL在哪里
SELECT employees.manager, timeworked.fiscalmonth, kronoscodes.projectname,
Sum(timeworked.hoursworked) AS SumOfHoursWorked
FROM employees INNER JOIN
(kronoscodes INNER JOIN timeworked
ON kronoscodes.projectcode = timeworked.projectcode
) ON employees.[employee id] = timeworked.employeeid
GROUP BY employees.manager, timeworked.fiscalmonth, kronoscodes.projectname;
结果看起来像这样
manager fiscalmonth projectname SumOfHoursWorked
Manager A janfy13 Project 101 16
Manager A janfy13 Project 102 8
Manager B janfy13 Project 101 11
嗯,没有提到“经理B”的“Project 102”,根本没有提到“Project 103”。尽管如此,这是一个很好的开始,所以让我们将其保存为“ProjectSumsByManager_innerJoin”。(以后可能有用……提示,提示。)
我们想查看所有项目,所以我们右键单击 [timeworked] 和 [kronoscodes] 之间的连接,选择“Join Properties”,然后选择选项“Include ALL records from 'kronoscodes' and only those records from 'timeworked'连接字段相等的地方。”
不幸的是,当我们尝试运行查询时,我们得到了令人讨厌的“模糊外部连接”消息:
SQL 语句无法执行,因为它包含不明确的外部连接。要强制首先执行其中一个连接,请创建一个单独的查询来执行第一个连接,然后将该查询包含在您的 SQL 语句中。
好的,所以我们只使用该连接创建一个单独的查询:
SQL在哪里
SELECT kronoscodes.projectcode, timeworked.employeeid,
timeworked.fiscalmonth, timeworked.hoursworked
FROM kronoscodes LEFT JOIN timeworked
ON kronoscodes.projectcode = timeworked.projectcode;
结果看起来像这样。
projectcode employeeid fiscalmonth hoursworked
101 1 janfy13 16
101 2 janfy13 11
102 1 janfy13 8
103
嗯,“项目 103”在那里,但它没有员工 ID,所以我们无法链接到 [员工] 记录并获得经理。此外,“项目 102”仍然只与“员工 1”(“经理 A”)相关联,因此“经理 B”仍然不会出现。这种方法看起来并不是特别有希望。
也许我们真正想要的只是所有项目和所有经理的列表:
SELECT DISTINCT kronoscodes.projectname, employees.manager
FROM kronoscodes, employees;
返回
projectcode manager
Project 101 Manager A
Project 101 Manager B
Project 102 Manager A
Project 102 Manager B
Project 103 Manager A
Project 103 Manager B
如果我们在 Access 中创建一个新查询,将该 SQL 语句键入(或粘贴)到 SQL 视图中,然后将其保存为“Project_Manager_map”,我们可以将其与上面的第一个查询 LEFT JOIN ,并得到
SQL在哪里
SELECT Project_Manager_map.manager, ProjectSumsByManager_innerJoin.fiscalmonth,
Project_Manager_map.projectname, ProjectSumsByManager_innerJoin.SumOfHoursWorked
FROM Project_Manager_map LEFT JOIN ProjectSumsByManager_innerJoin ON
(Project_Manager_map.manager = ProjectSumsByManager_innerJoin.manager)
AND (Project_Manager_map.projectname = ProjectSumsByManager_innerJoin.projectname);
结果是
manager fiscalmonth projectname SumOfHoursWorked
Manager A janfy13 Project 101 16
Manager B janfy13 Project 101 11
Manager A janfy13 Project 102 8
Manager B Project 102
Manager A Project 103
Manager B Project 103