如何摆脱SQL Server中内部联接的重复

时间:2011-08-30 10:01:20

标签: sql sql-server sql-server-2008

我正在加入3个表OpportunityLeadNotes

Select 
     Distinct O.oppo_jobid, O.oppo_status,
     cast(N.Note_Note as NCHAR) as Notes 
from Opportunity O, Notes N
Inner join Notes on o.Oppo_OpportunityId = Notes.Note_ForeignId 
Inner join Lead on o.Oppo_OpportunityId = Lead.Lead_OpportunityID

我正在重复。如何在使用内连接时避免重复?

主表格为OpportunityNotesopportunity id进行比较,Notes表格中有许多具有相同商机的记录,因此会出现重复。现在,我可以在比较表格和获取最后更新的笔记时避免重复。

提前致谢...

1 个答案:

答案 0 :(得分:4)

确保您不会意外地在这里做笛卡尔积:

from Opportunity O, Notes N

这应该只是

from Opportunity O

您已经在INNER加入Notes表格了....

所以这里的查询应该不会返回任何重复:

Select 
     O.oppo_jobid, O.oppo_status,
     cast(N.Note_Note as NCHAR) as Notes 
from dbo.Opportunity O
Inner join dbo.Notes on o.Oppo_OpportunityId = Notes.Note_ForeignId 
Inner join dbo.Lead on o.Oppo_OpportunityId = Lead.Lead_OpportunityID

更新:如果您只想获得每个商机的最新note,请使用此查询:

;WITH MostRecent AS
(
    SELECT 
        O.oppo_jobid, O.oppo_status,
        cast(N.Note_Note as NCHAR) as Notes,
        ROW_NUMBER() OVER (PARTITION BY o.Oppo_OpportunityId 
                           ORDER BY n.Note_DateTimeStamp DESC) AS 'RowNum'
    FROM dbo.Opportunity O
    INNER JOIN dbo.Notes on o.Oppo_OpportunityId = Notes.Note_ForeignId 
)
SELECT *
FROM MostRecent
WHERE RowNum = 1