2017-07-14 103 views
0

我是一個相對的新手上訪問一個問題遠遠超出了我的技能更新查詢從第二個表

我在包含名字叫做現有員工Access表中存儲關於僱員的信息,姓氏使用最近數值,員工ID等。

由於員工經常更換班次/職位,我需要一種方法來存儲職位名稱,班次等歷史記錄,而不必爲具有大量冗餘數據的員工存儲兩條記錄。

所以我創建了一個名爲分配歷史與員工ID,那裏可以爲同一僱員的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); 

有關如何將此查詢更改爲當前員工更新的幫助?或者有更好的方式來格式化和存儲這些信息?

回答

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 
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]) & "#")