使用第二个表中的最新值更新查询

时间:2017-07-14 17:36:54

标签: sql vba ms-access access-vba ms-access-2013

我是Access的相对新手,其问题远远高于我的技能

我将有关Employees的信息存储在名为Current Employees的Access表中,该表包含名字,姓氏,员工ID等。

由于员工经常更换班次/职位,我需要一种方法来存储他们的职位,班次等历史记录,而无需为拥有大量冗余数据的员工存储两条记录。

所以我创建了第二个名为Assignment History的表,其中包含Employee ID之间的关系,其中可以有多个相同Employee ID的条目,看起来像

Employee ID | Assigned As Of | Job Title | Shift
1234        | 01/01/2017     | Manager   | A
1234        | 12/01/2016     | Salesman  | A 
5678        | 12/01/2016     | Salesman  | B

现在出于各种形式的原因,我想把最近的价值放回到我的第一个表当前员工的当前职位位置,如此

Employee ID | FName         | Last Name | Current Job
1234        | John          | Smith     | Manager
5678        | Steve         | Adams     | Salesman

我能够得到的最接近的是创建表查询到第三个表CurrAssign,其中代码是

SELECT a.* 
INTO CurrAssign
FROM AssignmentHistory AS a 
INNER JOIN (
     SELECT max(a.AssignedAsOf) AS LatestDate, a.EmployeeID 
     FROM AssignmentHistory AS a GROUP BY a.EmployeeID)  
AS SubMax 
ON (a.EmployeeID = SubMax.EmployeeID) 
AND (a.AssignedAsOf = SubMax.LatestDate);

有关如何将此查询更改为当前员工的更新的任何帮助?或者有更好的方法来格式化和存储这些信息吗?

2 个答案:

答案 0 :(得分:0)

你可以尝试一个简单的"查找"做法。这会有用吗?

SELECT ce.EmployeeID, ce.FName, ce.LName,
(SELECT TOP 1 ah.[Job Title] FROM AssignmentHistory ah WHERE ah.EmployeeID = ce.EmployeeID ORDER BY ah.AssignedAsOf DESC) AS CurrentJob--Look up Current Job
FROM CurrentEmployee ce

答案 1 :(得分:0)

由于MS Access要求更新查询为updateable,因此请考虑在查询中使用嵌套域聚合DLookUpDMax

UPDATE Employees e    
SET e.[Current Job] = DLookUp("[Job Title]", "[Assignment History]", 
                              "[Employee ID]=" & e.[Employee ID] & 
                              " AND [Assigned As Of]=#" & 
                              DMax("[Assigned As Of]", "[Assignment History]", 
                                   "[Employee ID]=" & e.[Employee ID]) & "#")