在一个必须满足所有条件的字段上使用多个条件进行查询

时间:2014-05-09 13:33:50

标签: sql ms-access-2010

我有一个查询,它会带回任何包含任何课程的人的列表。我需要一份列出所有课程并且没有过期的人员。我不希望看到课程列表只列出拥有全部5门课程的人员。我正在使用MS Access 2010 SQL。

SELECT tblEmployees.LName, tblEmployees.FName, tblEmployees.Trade,
       tblEmployees.Title, tblTrainingHistory.Date, tblCourses.CourseName,
       IIf(IsNull(CourseLength),"",DateAdd("m",[CourseLength],[Date])) AS ExpiryDate
FROM tblEmployees LEFT JOIN (tblCourses RIGHT JOIN tblTrainingHistory ON
      tblCourses.CourseID = tblTrainingHistory.CourseID) 
       ON tblEmployees.EmpID = tblTrainingHistory.EmpID
WHERE 
    (((tblCourses.CourseName) 
      In ("Confined Space","Manwatch","Ventis MX4","First Aid","CPR")) 
   AND ((IIf(IsNull([CourseLength]),Now(),DateAdd("m",[CourseLength],[Date])))>Now())
   AND ((tblEmployees.Active)=True))
GROUP BY tblEmployees.LName, tblEmployees.FName, tblEmployees.Trade, 
      tblEmployees.Title, tblTrainingHistory.Date, tblCourses.CourseName,
      tblEmployees.EmpID, tblCourses.CourseLength    ;

1 个答案:

答案 0 :(得分:0)

使用结果表,按所有员工特征分组,只选择那些计数(*)等于5的人(因为你有5门课程)。

SELECT LName, FName, Trade, Title, count(*) as courses
FROM(
SELECT tblEmployees.LName, tblEmployees.FName, tblEmployees.Trade,
       tblEmployees.Title, tblTrainingHistory.Date, tblCourses.CourseName,
       IIf(IsNull(CourseLength),"",DateAdd("m",[CourseLength],[Date])) AS ExpiryDate
FROM tblEmployees LEFT JOIN (tblCourses RIGHT JOIN tblTrainingHistory ON
      tblCourses.CourseID = tblTrainingHistory.CourseID) 
       ON tblEmployees.EmpID = tblTrainingHistory.EmpID
WHERE 
    (((tblCourses.CourseName) 
      In ("Confined Space","Manwatch","Ventis MX4","First Aid","CPR")) 
   AND ((IIf(IsNull([CourseLength]),Now(),DateAdd("m",[CourseLength],[Date])))>Now())
   AND ((tblEmployees.Active)=True))
GROUP BY tblEmployees.LName, tblEmployees.FName, tblEmployees.Trade, 
      tblEmployees.Title, tblTrainingHistory.Date, tblCourses.CourseName,
      tblEmployees.EmpID, tblCourses.CourseLength ) results
GROUP BY LName, FName, Trade, Title
HAVING count(*) = 5  ;

子查询可能没有必要,但由于您的查询非常复杂,我不想搞砸它。您可以尝试仅在一个查询中执行此操作

请参阅related question with simpler tables