Selecting additional data/values to display as column in query or in form

这一生的挚爱 提交于 2021-01-29 06:10:29

问题


I have an employee index, that I need to run queries on for each employee, and display that output along with the original employee.

So say the employee index has an ID, batch, status, and multiple other columns. I have a table where I keep track of every time a column in the employee index changes. I want to display and later export dates of when certain columns use to equal other values, right along side the original employee row.

Naturally I tried creating a form to display multiple value, added a text box to hold my extra information, and changed the value of the text box for each Form_Current event in VBA.

Private Sub Form_Current()
    Me.txtPhaseOne = SimpleLookup("SELECT TOP 1 ChangeDate FROM EmployeeVariables WHERE VariableName = ""Batch"" AND EmployeeID = " & Me.Recordset("ID Number") & " ORDER BY ChangeDate ASC", "ChangeDate")
End Sub

It seemed to work at first...

Until I realized the dates were set to whatever the current record date should be [second example3

So then I tried a join:

SELECT
  EmployeeIndex.[ID Number],
  EmployeeIndex.Batch,
  EmployeeIndex.Status,
  EmployeeIndex.[First name],
  EmployeeIndex.[Last name],
  EVA.ChangeDate as Phase1
FROM
  EmployeeIndex
  (SELECT TOP 1 ChangeDate FROM EmployeeVariables WHERE EmployeeID = EmployeeIndex.[ID Number] ORDER BY CHangeDate) EVA

Which would work, if I could some how prefetch EmployeeIndex.[ID Number]. (I didn't name these columns) Except I haven't got the slightest clue and I'm running on fumes.

SELECT
  EmployeeIndex.[ID Number],
  EmployeeIndex.Batch,
  EmployeeIndex.Status,
  EmployeeIndex.[First name],
  EmployeeIndex.[Last name],
  EVA.ChangeDate as Phase1
FROM
  EmployeeIndex
INNER JOIN
  (SELECT TOP 1 EmployeeID, ChangeDate FROM EmployeeVariables WHERE ORDER BY ChangeDate) EVA
    ON EmployeeIndex.[ID Number] = EVA.EmployeeID

回答1:


Try with a subquery:

SELECT
    EmployeeIndex.[ID Number],
    EmployeeIndex.Batch,
    EmployeeIndex.Status,
    EmployeeIndex.[First name],
    EmployeeIndex.[Last name],
        (SELECT Max(EVA.ChangeDate)
        FROM EmployeeVariables AS EVA
        WHERE EVA.EmployeeID = EmployeeIndex.[ID Number]) AS Phase1
FROM
    EmployeeIndex



回答2:


Cross Apply will be perfect for your TOP 1 case, as it will run for each employeeID rather than just joining on 1



来源:https://stackoverflow.com/questions/64113037/selecting-additional-data-values-to-display-as-column-in-query-or-in-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!