我需要能够计算tblOptyRecordsHistorical
与主表相关的辅助表中的记录数tblOptyRecordsCurrent
。
表完全相同,主表包含当前的“每日快照”,辅助表包含以前的每日快照。
我有许多使用以下基本语法的标志:
(SELECT COUNT(OpportunityRecordID) AS Expr1
FROM dbo.tblOptyRecordsHistorical AS hist
WHERE (OpportunityGlobalCRMId = curr.OpportunityGlobalCRMId))
AS prevEntries,
这工作正常。但是有一个标志,我需要统计历史表中的记录数,但是逻辑更复杂,并且取决于主表中的值:
SELECT OpportunityGlobalCRMId,
(SELECT SUM(CASE WHEN curr.PartnerGlobalCRMID IS NULL THEN CASE WHEN
hist.IgnoreOpportunity != 0 THEN 1 ELSE 0 END ELSE CASE
WHEN curr.CustomerAccountID IS NULL THEN CASE WHEN hist.IgnoreOpportunity = 1 AND
hist.PartnerGlobalCRMID = curr.PartnerGlobalCRMID THEN 1 ELSE 0 END ELSE CASE WHEN
hist.IgnoreOpportunity = 1 AND CONVERT(varchar, hist.CustomerAccountID) +
hist.PartnerGlobalCRMID = CONVERT(varchar, curr.CustomerAccountID) +
curr.PartnerGlobalCRMID AND hist.OpptyIncentiveCreatedDate =
curr.OpptyIncentiveCreatedDate THEN 1 ELSE 0 END END END) AS Expr1 FROM
dbo.tblOptyRecordsHistorical AS hist WHERE (OpportunityGlobalCRMId =
curr.OpportunityGlobalCRMId)) AS prevIgnored
FROM dbo.tblOptyRecordsCurrent AS curr
除了初始的OpportunityGlobalCRMID
. 这会导致以下错误:Multiple columns are specified in an aggregated expression containing an outer reference. If an expression is being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression.