我正在加入3个表Opportunity
,Lead
,Notes
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
我正在重复。如何在使用内连接时避免重复?
主表格为Opportunity
,Notes
与opportunity id
进行比较,Notes
表格中有许多具有相同商机的记录,因此会出现重复。现在,我可以在比较表格和获取最后更新的笔记时避免重复。
提前致谢...
答案 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