access超级表

du7egjpx  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(313)

我一直想把两张table合并起来,但做不成。正在尝试将雇员数添加到另一个表中。

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)

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

pqwbnv8z

pqwbnv8z1#

因为您正在运行不同的分组级别聚合查询(首先按jobid和department,然后只按jobid),所以请考虑将它们作为派生表(即中的嵌套子查询)连接起来 FROM 或者 JOIN 条款):

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
oyt4ldly

oyt4ldly2#

我相信阿什利多格说的是真的。但是,由于您使用的是ms-access,这种类型的sql字符串很可能无法正常工作。
据我所知,没有任何版本的msaccess在这种情况下支持sql(但我可能错了)
如果上面提到的不起作用,请尝试以下方法:

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

编辑:
为简单起见(这是在查询[design tab]的设计视图中):

deyfvvtc

deyfvvtc3#

你只需要一个简单的 JOIN . (更多信息请点击此处)
将示例表中的数据基于 JobID :

SELECT
  [Training History].*,
  JobID.*
FROM
  [Training History] left**inner join**JobID
  ON [Training History].JobID = Job.JobID

这只是连接的最简单形式;您可以做更多的工作,这可能会更好地应用于您的实际数据和需求。google“连接access中的表”。
另外,access的查询设计器使完成这样的任务变得更加容易,因为它为您“编写”sql。

相关问题