2013-10-14 79 views
0

你好我有這個SQL在下面,但我有一個問題,我保持考勤記錄在考勤表和筆記在StaffComments表中,但我也有一個表ContractorsComments女巫使用相同的出勤表,並在某些情況下NotesID柱已經漲了一倍SQL語句LEFT JOIN不能得到結果我正在尋找

承包商有不同的PRN員工我試圖用

WHERE dbo.StaffComments.PRN = 15458 AND dbo.Attendance.PRN = 15458

但這會導致它只顯示記錄在兩個表中找到匹配的記錄ES

我需要的SQL顯示在dbo.StaffComments表相同的PRN所有Notes,但只記錄在dbo.Attendance

SELECT Comments, PRN, id, DateMade, UserID, Reason, EventDate, AttendanceID, Sdate, Edate 
     FROM ( 
     SELECT dbo.StaffComments.Comments, dbo.StaffComments.PRN, dbo.StaffComments.id, dbo.StaffComments.DateMade, dbo.StaffComments.UserID, dbo.StaffComments.Reason, 
     dbo.StaffComments.EventDate, dbo.Attendance.id AS AttendanceID, dbo.Attendance.Sdate, dbo.Attendance.Edate, ROW_NUMBER() OVER (ORDER BY dbo.StaffComments.ID DESC) AS RowNum 
     FROM dbo.StaffComments 
     LEFT JOIN dbo.Attendance 
     ON dbo.StaffComments.id = dbo.Attendance.NoteID  
     WHERE dbo.StaffComments.PRN = 15458 
     ) AS notes 
     WHERE notes.RowNum BETWEEN 1 AND 100 

回答

1

更新您的條款加入關於PRN

LEFT JOIN dbo.Attendance 
     ON dbo.StaffComments.id = dbo.Attendance.NoteID  
     AND dbo.StaffComments.PRN = dbo.Attendance.PRN 
     WHERE dbo.StaffComments.PRN = 15458 

您更新的查詢將是這樣的:

SELECT Comments, PRN, id, DateMade, UserID, Reason, EventDate, AttendanceID, Sdate, Edate 
     FROM ( 
     SELECT dbo.StaffComments.Comments, dbo.StaffComments.PRN, dbo.StaffComments.id, dbo.StaffComments.DateMade, dbo.StaffComments.UserID, dbo.StaffComments.Reason, 
     dbo.StaffComments.EventDate, dbo.Attendance.id AS AttendanceID, dbo.Attendance.Sdate, dbo.Attendance.Edate, ROW_NUMBER() OVER (ORDER BY dbo.StaffComments.ID DESC) AS RowNum 
     FROM dbo.StaffComments 
     LEFT JOIN dbo.Attendance 
     ON dbo.StaffComments.id = dbo.Attendance.NoteID 
     AND dbo.StaffComments.PRN = dbo.Attendance.PRN 
     WHERE dbo.StaffComments.PRN = 15458 
     ) AS notes 
     WHERE notes.RowNum BETWEEN 1 AND 100 
0

你爲什麼要參加在staffcomments.id和attendance.noteid ?

您需要像以前一樣加入PRN,但需要外連接。

SELECT Comments, PRN, id, DateMade, UserID, Reason, EventDate, AttendanceID, Sdate, Edate 
     FROM ( 
     SELECT dbo.StaffComments.Comments, dbo.StaffComments.PRN, dbo.StaffComments.id, dbo.StaffComments.DateMade, dbo.StaffComments.UserID, dbo.StaffComments.Reason, 
     dbo.StaffComments.EventDate, dbo.Attendance.id AS AttendanceID, dbo.Attendance.Sdate, dbo.Attendance.Edate, ROW_NUMBER() OVER (ORDER BY dbo.StaffComments.ID DESC) AS RowNum 
     FROM dbo.StaffComments 
     LEFT OUTER JOIN dbo.Attendance 
     ON dbo.StaffComments.PRN = dbo.Attendance.PRN  
     WHERE dbo.StaffComments.PRN = 15458 
     ) AS notes 
     WHERE notes.RowNum BETWEEN 1 AND 100 
+0

我已經試過你的代碼,但我仍然只能得到行是這兩個dbo.StaffComments和dbo.Attendance 掛在抱歉,從我能看到有1條記錄顯示現在形成dbo.StaffComments並匹配它60 dbo.Attendance表中的記錄 – Anthony