1

我需要能够计算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.

4

1 回答 1

2

SQL Server 不喜欢在聚合子查询表达式中混合内部(hist表)和外部(表)。这里curr有一些解释。

建议的解决方案是在子查询中重新包含外部表,加入它的键,以使所有引用都在内部。在您的情况下,这意味着将tblOptyRecordsCurrent表放在子查询中,如下所示:

SELECT OpportunityGlobalCRMId, 
    (SELECT SUM(CASE 
                WHEN curr2.PartnerGlobalCRMID IS NULL 
                THEN CASE WHEN hist.IgnoreOpportunity != 0 THEN 1 ELSE 0 END 
                ELSE CASE 
                        WHEN curr2.CustomerAccountID IS NULL 
                        THEN CASE 
                            WHEN hist.IgnoreOpportunity = 1 AND hist.PartnerGlobalCRMID = curr2.PartnerGlobalCRMID THEN 1 ELSE 0 END 
                        ELSE CASE 
                            WHEN hist.IgnoreOpportunity = 1 
                                AND CONVERT(varchar, hist.CustomerAccountID) + hist.PartnerGlobalCRMID 
                                    = CONVERT(varchar, curr2.CustomerAccountID) + curr2.PartnerGlobalCRMID 
                                AND hist.OpptyIncentiveCreatedDate = curr2.OpptyIncentiveCreatedDate 
                            THEN 1 
                            ELSE 0 
                            END 
                    END 
            END) AS Expr1 
    FROM dbo.tblOptyRecordsHistorical AS hist 
        inner join dbo.tblOptyRecordsCurrent AS curr2 on curr2.OpportunityGlobalCRMId = hist.OpportunityGlobalCRMId
    WHERE curr2.OpportunityGlobalCRMId = curr.OpportunityGlobalCRMId) AS prevIgnored
FROM dbo.tblOptyRecordsCurrent AS curr  

但是没有测试过代码。

于 2013-08-13T10:56:06.667 回答