0

您好,我在下面有这个 SQL,但我遇到了问题,我将出勤记录保存在出勤表中,并将注释保存在 StaffComments 表中,但我也有一个表 ContractorsComments,女巫在某些情况下使用相同的出勤表和 NotesID 列翻了一番

承包商对我尝试使用的员工有不同的 PRN

其中 dbo.StaffComments.PRN = 15458 和 dbo.Attendance.PRN = 15458

但这会导致它仅显示在两个表中找到匹配项的记录

我需要 SQL 来显示 dbo.StaffComments 表中的所有注释,但只在 dbo.Attendance 中显示具有相同 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 JOIN dbo.Attendance
        ON dbo.StaffComments.id = dbo.Attendance.NoteID     
        WHERE dbo.StaffComments.PRN = 15458  
        ) AS notes 
        WHERE notes.RowNum BETWEEN 1 AND 100
4

2 回答 2

1

将您的 ON 子句更新为 JOIN on 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
于 2013-10-14T03:23:08.967 回答
0

你为什么要加入 staffcomments.id 和 admission.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
于 2013-10-14T02:57:38.877 回答