访问超级坚持与表

时间:2018-05-02 16:10:45

标签: mysql sql ms-access

我一直试图将两张桌子组合在一起,但却无法完成。尝试将员工人数添加到另一个表中。 enter image description here enter image description here

SELECT [Training History].JobID,(
       SELECT Job.Department 
       FROM Job 
       WHERE [Training History].JobID = Job.JobID) 
       AS Department, 
SUM([Expenditure]) AS ExpenditureOfJob 
     FROM [Training History] 
     GROUP BY [Training History].JobID,
(SELECT COUNT (*) AS [Number of Employees] 
     FROM Employee 
     GROUP BY JobID)
;

也试过;

(SELECT COUNT (*) AS [Number of Employees] 
     FROM Employee 
    WHERE [Training History].JobID = Employee.JobID
 GROUP BY JobID)

说最后一位有语法错误,但我找不到它。

3 个答案:

答案 0 :(得分:1)

您只需要简单JOIN 。 (More info here

根据JobID

组合示例表格中的数据
SELECT
  [Training History].*,
  JobID.*
FROM
  [Training History] left **inner join** JobID
  ON [Training History].JobID = Job.JobID

这是最简单的联接形式;你可以做的更多,可能更适合你的真实数据和需求。 Google“在Access中加入表格”。

此外,Access的查询设计器可以更轻松地完成这样的任务,因为它会为您“编写”SQL。

答案 1 :(得分:1)

因为您正在运行不同的分组级聚合查询(首先是 JobID 部门,然后仅运行 JobID ),请考虑加入它们作为派生表(即FROMJOIN子句中的嵌套子查询):

SELECT agg1.JobID, agg1.Department, agg1.ExpenditureOfJob, agg2.[Number of Employees]
FROM
  (SELECT t.JobID, j.Department, SUM([Expenditure]) AS ExpenditureOfJob 
   FROM [Training History] t
   INNER JOIN Job j ON t.JobID = j.JobID
   GROUP BY t.JobID, j.Department) As agg1

   INNER JOIN
  (SELECT t.JobID, Count(*) AS [Number of Employees]
   FROM [Training History] t
   GROUP BY t.JobID) As agg2

ON agg1.JobID = agg2.JobID

或加入已保存的查询:

SELECT agg1.*, agg2.[Number of Employees]
FROM
  mySavedQueryAgg1 as agg1

INNER JOIN
  mySavedQueryAgg2 as agg2

ON agg1.JobID = agg2.JobID

答案 2 :(得分:0)

我相信ashleedawg说的是真的。但是,由于您使用的是MS Access,因此该类型的SQL字符串很可能无法正常工作。

据我所知,MS Access的任何版本都不支持该上下文中的SQL。 (虽然我可能错了)

如果提到的内容不起作用,请尝试以下方法:

SELECT * 
FROM [Training History]
INNER JOIN Employee ON Employee.JobID = [Training History].JobID

编辑:

为简单起见(这是在查询[Design Tab]的设计视图中):

enter image description here