0

在我尝试计算每个帐户 (ACCT) 有多少付款 (trans_key) 之前,此查询工作正常。

无法对包含聚合或子查询的表达式执行聚合函数。

SELECT CONVERT(VARCHAR,D.ACCT) ClientReference,
    ISNULL((SELECT S.SD_DATA 
            FROM SDDATA AS S 
            WHERE S.DEBT_KEY=D.DEBT_KEY AND S.SD_KEY=36),' ') Division,
    REPLACE(RTRIM(DB.FNAME)+' '+RTRIM(DB.LNAME),',',' ') AccountHolder,
    CONVERT(VARCHAR,D.DOR,101) ListedDate,
    ISNULL((SELECT SA.SD_DATA 
            FROM SDDATA AS SA 
            WHERE SA.DEBT_KEY=D.DEBT_KEY 
                AND SA.SD_KEY=2),' ') AssignmentType,
    CONVERT(VARCHAR,D.BAL) CurrentBalance,
    CONVERT(VARCHAR,D.ASSIGNED) PlacementBalance,
    CONVERT(VARCHAR,isnull((SELECT -1*SUM(TD.DIST_AMT) 
                            FROM TRANSDIST AS TD,TRANS AS T,TRANS_CODE AS TC 
                            WHERE T.DEBT_KEY=D.DEBT_KEY 
                                AND TD.TRANS_KEY=T.TRANS_KEY  
                                AND TC.TRANS_CODE=T.TRANS_CODE 
                                AND TC.TRANS_BILL=1),0)) AmountRecovered,
    CONVERT(VARCHAR,isnull((SELECT (-1*SUM(TD.DIST_AMT)+SUM(DIST_NET)) 
                            FROM TRANSDIST AS TD,TRANS AS T,TRANS_CODE AS TC 
                            WHERE T.DEBT_KEY=D.DEBT_KEY 
                                AND TD.TRANS_KEY=T.TRANS_KEY  
                                AND TC.TRANS_CODE=T.TRANS_CODE 
                                AND TC.TRANS_BILL=1),0)) AmountApplied,
    CONVERT(VARCHAR,isnull((SELECT (-1*SUM(DIST_NET)) 
                            FROM TRANSDIST AS TD,TRANS AS T,TRANS_CODE AS TC 
                            WHERE T.DEBT_KEY=D.DEBT_KEY 
                                AND TD.TRANS_KEY=T.TRANS_KEY  
                                AND TC.TRANS_CODE=T.TRANS_CODE 
                                AND TC.TRANS_BILL=1),0)) SMAFees,
    COUNT((select trans_key from trans)) as Payments 
FROM DEBT AS D,DEBTOR AS DB,STATUS AS ST
WHERE ST.STAT_KEY=D.STAT_KEY
    AND DB.DEBTOR_KEY=D.DEBTOR_KEY
    AND D.CLIENT_KEY =43 
    AND ST.CATEGORY='A'

当弄乱计数聚合函数时,我能够获取一些数据,但不是正确的计数。它只是给了我表格内所有“付款”的计数,而不是每个 ACCT 的金额。

4

1 回答 1

1

我觉得您的查询是以一种非常奇怪的方式编写的,这将使其难以调试。一些想法:

  • 停止转换您选择的所有内容(至少在获得所需结果之前)。这将使您的代码更简洁,更易于调试
  • 如果可能,请停止选择语句中的子查询。例如:

    ISNULL((从 SDDATA 中选择 SA.SD_DATA 作为 SA WHERE SA.DEBT_KEY=D.DEBT_KEY AND SA.SD_KEY=2),' ') AssignmentType,

可以转换为

ISNULL(SA.SD_DATA,' ')
...
...
FROM DEBT AS D
LEFT JOIN SDDATA AS SA 
ON sa.DEBT_KEY = d.DEBT_KEY
  • 停止使用隐式连接

  • 阅读 GROUP BY 如何与聚合函数一起工作。

这不是针对您的确切问题的解决方案,但是如果您想解决此问题,则需要将此查询置于可行状态并进行一些基础研究。

于 2012-08-08T16:20:02.163 回答