您好我在下面有这个SQL但是我遇到了问题我将出勤记录保存在出勤表和StaffComments表中的注释但我也有一个表ContractorsComments女巫使用相同的出勤表和NotesID列在某些情况下增加了一倍
承包商与我试图使用的员工有不同的PRN
在哪里dbo.StaffComments.PRN = 15458 AND dbo.Attendance.PRN = 15458
但这导致它只显示两个表中找到匹配的记录
我需要SQL来显示dbo.StaffComments表中的所有Notes,但只显示dbo中的SAME PRN记录.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
答案 0 :(得分:1)
将您的ON子句更新为PRN上的JOIN
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
答案 1 :(得分: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