如何避免此Access SQL kludge?

时间:2011-05-10 17:29:55

标签: sql ms-access

目标是从每个“资格”的最新作业返回信息。如果有两个具有相同日期的作业,则每个“资格”仍然只返回一行,并且选择的作业是任意的。

目前的方法:

qCurrentAssignment_sub:

SELECT tblAssignment.EligibilityID, Max(DateAdd("s",[AssignmentID] Mod 10000,[AssignmentDate])) AS DatePlusIDMod10000
FROM tblAssignment
GROUP BY tblAssignment.EligibilityID;

qCurrentAssignment:

SELECT tblAssignment.AssignedTo, tblAssignment.AssignedBy, tblAssignment.Method, tblAssignment.AssignmentDate
FROM qCurrentAssignment_sub INNER JOIN tblAssignment ON 
    (qCurrentAssignment_sub.EligibilityID = tblAssignment.EligibilityID) AND 
    (qCurrentAssignment_sub.DatePlusIDMod10000 = DateAdd("s",[AssignmentID] Mod 10000,[AssignmentDate]));

1 个答案:

答案 0 :(得分:1)

从评论中更新

如果给出

  • 每个assignmentid的多次分配
  • 您希望与max assignmentDate
  • 关联的assignmentid
  • 如果max(assignmentDate)存在多个assignmentid,那么您需要max assignmentid

将qCurrentAssignment_sub更改为

qCurrentAssignment_sub

  
  SELECT
        eligibilityid,
        MAX(assignmentid) assignmentid

    FROM
        tblassignment 
        INNER JOIN 
        (SELECT tblassignment.eligibilityid, 
               MAX(AssignmentDate) AssignmentDate 
        FROM   tblassignment 
        GROUP  BY tblassignment.eligibilityid) maxAssignmentDate
        ON tblassignment.eligibilityid = maxAssignmentDate.eligibilityid
           and maxAssignmentDate.AssignmentDate = maxAssignmentDate.AssignmentDate
    GROUP BY 
        eligibilityid

然后在assignmentid上加入tblassignment。这使得连接也更加清洁

qCurrentAssignment

SELECT tblassignment.assignedto, 
       tblassignment.assignedby, 
       tblassignment.method, 
       tblassignment.assignmentdate 
FROM   tblassignment 
       INNER JOIN qcurrentassignment_sub 
         ON tblassignment.assignmentid = qcurrentassignment_sub.assignmentid