2014-05-09 17 views
0

我有一個查詢,可以找回任何具有任何課程的任何人的列表。我需要列出誰擁有所有課程並且沒有過期。我不想看到課程列表只是列出了所有5門課程的人員名單。我正在使用MS Access 2010 SQL。在滿足ALL條件的一個字段上使用多個條件進行查詢

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 ; 
+0

如果你想提高你獲得幫助的機會,它通常是一個好主意,提供一個SQL小提琴 –

+0

什麼是SQL小提琴? – Stacey

+0

當涉及到SO和SQL查詢問題時,一個非常有用的工具:http://sqlfiddle.com/ –

回答

0

使用你的結果表,由集團全體員工的特點和只選擇那些誰擁有COUNT(*)等於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

+0

當我添加HAVING(((Count(*))= 5))時,它不會返回任何數據。 – Stacey

+0

我試過了,它返回的語法錯誤(缺少運算符)在查詢表達式標題Where Count(*)= 5; – Stacey

+0

對不起,使用有,不在 –