I am trying to run the below query but keep having an issue with people whom have both requirements in my Case statement being pulled out for each instance when i only want a single record to be pulled, even if they have both conditions.
SELECT DISTINCT
SyCampus.Descrip AS 'Campus',
dbo.rpt_adAttendanceDetail_vw.instructorname AS 'Instructor Name',
dbo.rpt_adAttendanceDetail_vw.classcode AS 'Class Code',
dbo.rpt_adAttendanceDetail_vw.section AS 'Section',
dbo.rpt_adAttendanceDetail_vw.classdescrip AS 'Class',
RTRIM(SyStudent.FirstName) + ' ' + ' ' + RTRIM(SyStudent.LastName) AS 'Student Name',
dbo.rpt_adAttendanceDetail_vw.stunum AS 'Student Number',
CASE WHEN CmEvent.CmtemplateID IN (714, 716, 732,734)THEN 'YES' ELSE 'NO' END AS 'Instructor Contact'
FROM
dbo.rpt_adAttendanceDetail_vw
JOIN
SyStudent
ON SyStudent.SyStudentID = dbo.rpt_adAttendanceDetail_vw.SyStudentID
JOIN
SyCampus
ON Sycampus.SycampusID = SyStudent.SyCampusID
JOIN
CmEvent
ON CmEvent.SyStudentID = SyStudent.SyStudentID
WHERE dbo.rpt_adAttendanceDetail_vw.AttMin = '0'
AND dbo.rpt_adAttendanceDetail_vw.date = DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0) -1
AND SyStudent.SySchoolStatusID IN (13, 129, 130, 132, 72, 59, 122, 14)
AND dbo.rpt_adAttendanceDetail_vw.attendtype <> 'E'
AND CmEvent.CmEventStatusid = '2'
I’m assuming that you have a one-to-many relationship between SyStudent and CmEvent. Given that each SyStudent may have a corresponding CmEvent both in and out of the list (714, 716, 732,734) would explain why your query may return more than one record per SyStudent. If you’d like to know if a SyStudent has a CmEvent.CmtemplateID in the given list or not you can handle it in the join.
Consider the following changes to your query:
The two significant changes here are the left join and the case statement. Firstly, we’ve moved the CmEvent criteria into the left join. By doing this we will only join to records in the CmEvent that meets our criteria. This will leave out all of the CmEvent records whose template ID’s are outside of our list. Secondly, the case statement is changed. Now we are using the existence of a CmEvent.SyStudentID to determine if the SyStudent has a CmEvent.CmtemplateID in the given list. If the left join produces no match then know they do not.