我正在编写SQL查询但是我的联接/子查询有问题。 我有一个任务表,我想加入另一个表' tbl_Profile_Mortgage' 问题是task表有多个重复的clientID,所以加入它们会带回包括重复在内的所有内容。我已将其修改为仅查看具有' taskid = originatorId'的客户端ID。 这工作正常,但我想创建另一个连接,以显示我的任务表中的列,但因为我已在任务表中作为子查询完成连接,我无法引用任务列。希望这是有道理的。 我已经注释掉了我要添加的联接以及要显示的列ID。任何帮助将不胜感激。 谢谢
SELECT
pm.DateCompleted AS DateCompleted,
pm.DateAppRcvd AS DateAppRcvd,
pm.DatePAckaged AS DatePackaged,
pm.DateOffered AS DateOffered,
pm.DateAppIssued AS DateAppIssued,
pm.DatePassed AS DatePassed,
pm.DateCancelled AS DateCancelled,
pm.DateOfEnquiry AS DateOfEnquiry,
pm.Arrangementfee,
pm.Lender,
pm.DateDip,
cf.ClNTNME,
pm.dateDeclined,
pm.Procfeeexp,
pm.fk_ProfileId,
u.FullName AS Advisor,
pm.Source,
pm.AmountRequested,
c.CaseTypeDesc,
cf.ClientId,
--ISD.ISDESC,
pm.AmountRequested,
pl.SiteNameNum,
pl.SiteAddr1,
pl.SiteAddr2,
pl.SiteTown,
pl.SiteCounty,
pl.SitePostcode
FROM dbo.tbl_Profile_Mortgage AS pm
LEFT JOIN dbo.tbl_ClientFile AS cf
ON cf.ClientID = pm.ClientId
LEFT JOIN tbl_Profile_ProjectLand AS pl
ON pl.FK_ProfileId = pm.FK_ProfileId
LEFT JOIN tbl_User AS u
ON u.UserId = pm.UpdatedBy
LEFT JOIN dbo.tbl_CaseTypes AS c
ON c.CaseTypeId = pm.CaseType
LEFT JOIN
(
SELECT Distinct ClientId
FROM Tasks
WHERE TaskId = OriginatorId
)t
ON (t.clientid = pm.ClientId)
--LEFT JOIN dbo.tbl_DDInitialSource AS ISD
-- ON t.EnquirySource = ISD.ISId

答案 0 :(得分:0)
所以我采取了Dave Brown的建议,将max添加到子查询中并且它完美地工作,谢谢Dave
SELECT
pm.DateCompleted AS DateCompleted,
pm.DateAppRcvd AS DateAppRcvd,
pm.DatePAckaged AS DatePackaged,
pm.DateOffered AS DateOffered,
pm.DateAppIssued AS DateAppIssued,
pm.DatePassed AS DatePassed,
pm.DateCancelled AS DateCancelled,
pm.DateOfEnquiry AS DateOfEnquiry,
pm.Arrangementfee,
pm.Lender,
pm.DateDip,
--cf.ClNTNME,
pm.dateDeclined,
pm.Procfeeexp,
pm.fk_ProfileId,
u.FullName AS Advisor,
pm.Source,
pm.AmountRequested,
--c.CaseTypeDesc,
cf.ClientId,
ISD.ISDESC,
pm.AmountRequested,
pl.SiteNameNum,
pl.SiteAddr1,
pl.SiteAddr2,
pl.SiteTown,
pl.SiteCounty,
pl.SitePostcode
FROM dbo.tbl_Profile_Mortgage AS pm
LEFT JOIN dbo.tbl_ClientFile AS cf
ON cf.ClientID = pm.ClientId
LEFT JOIN tbl_Profile_ProjectLand AS pl
ON pl.FK_ProfileId = pm.FK_ProfileId
LEFT JOIN tbl_User AS u
ON u.UserId = pm.UpdatedBy
LEFT JOIN
(SELECT DISTINCT ClientID, MAX(enquirySource) AS enquirySource
FROM Tasks
GROUP BY clientID
) AS t
ON t.clientid = pm.ClientId
LEFT JOIN dbo.tbl_DDInitialSource AS ISD
ON t.EnquirySource = ISD.ISId